变量的类型
python是一门动态语言,使用变量时无需预先声明变量的类型,变量可以指向(引用)任何类型的对象
获取类型脚本
➜ python-manual cat var/type.py
import types
for m in dir(types):
if "Type" in m:
print m
常见类型说明
| 类型 | 说明 |
|---|---|
| NoneType | None类型 |
| BooleanType | 布尔类型 |
| FloatType | 浮点数类型 |
| IntType | 整数类型 |
| LongType | 长整数类型 |
| ComplexType | 复数对象 |
| StringType | 字节串类型 |
| UnicodeType | 字符串类型 |
| ListType | 列表类型 |
| TupleType | 元组类型 |
| DictType | 字典类型 |
| SliceType | 切片类型 |
| XRangeType | 范围对象 |
| FunctionType | 函数类型 |
| MethodType | 方法类型 |
| BuiltinFunctionType | 内置函数类型 |
| BuiltinMethodType | 内置方法类型 |
| UnboundMethodType | 未绑定方法类型 |
| LambdaType | Lambda函数类型 |
| ClassType | 类类型 |
| ModuleType | 模块类型 |
| FileType | 文件类型 |
| GeneratorType | 生成器类型 |
| CodeType | 代码对象类型 |
| FrameType | 代码栈帧对象 |
| TracebackType | 异常对象 |
变量类型判断
>>> import types
>>> s = '你好'
>>> type(s) == str
True
>>> type(s) == types.StringType
True
>>> type(s) == types.UnicodeType
False
>>> isinstance(s, basestring)
True
>>> u = u'你好'
>>> type(u) == types.StringType
False
>>> type(u) == unicode
True
>>> type(u) == types.UnicodeType
True
>>> isinstance(u, basestring)
True
type判断会有坑,isinstance判断更加准确,参见字符序列相关的字节和字符章节
变量的作用域
| 类型 | 说明 |
|---|---|
| 局部变量 | 函数和方法中的变量 |
| 实例变量 | 对象中的变量 |
| 类变量 | 类中的变量 |
| 模块变量 | 模块中的变量 |
| 未定义的变量 | 未赋值的变量 |
变量的作用域演示
不同作用域的变量的输出
➜ python-manual cat var/scope.py
var = 'global'
class Var(object):
var = "class"
def __init__(self):
self.var = "instance"
def test(self):
var = "method"
print var
print self.var
print var
obj = Var()
obj.test()
print var
test = Var.test
test()
➜ python-manual python var/scope.py
class
method
instance
global
Traceback (most recent call last):
File "var/scope.py", line 22, in <module>
test()
TypeError: unbound method test() must be called with Var instance as first argument (got nothing instead)
不同作用域的变量的修改
➜ python-manual cat var/scope.py
var = 'global'
class Var(object):
var = "class"
def __init__(self):
self.var = "instance"
def test(self):
global var
var = "update_global"
self.__class__.var = "update_class"
self.var = "update_instance"
obj = Var()
print var
print Var.var
print obj.var
obj.test()
print var
print Var.var
print obj.var
➜ python-manual python var/scope.py
global
class
instance
update_global
update_class
update_instance
修改全局变量需要
global标识,否则就是定义一个同名的局部变量