为什么要记住class属性?
问题描述:
下面是一个简单的Python模块:为什么要记住class属性?
# foo.py
class Foo(object):
a = {}
def __init__(self):
print self.a
self.filla()
def filla(self):
for i in range(10):
self.a[str(i)] = i
那么我这样做在Python Shell:
$ python
Python 2.7.2 (default, Jan 13 2012, 17:11:09)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from foo import Foo
>>> f = Foo()
{}
>>> f = Foo()
{'1': 1, '0': 0, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8}
为什么第二次a
是不是空的?我错过了一些微不足道的东西吗?
答
问题是a
没有绑定。它是这个类的一个属性,而不是对象。你想要做这样的事情:
# foo.py
class Foo(object):
def __init__(self):
self.a = {}
print self.a
self.filla()
def filla(self):
for i in range(10):
self.a[str(i)] = i
答
它的类,而不是实例的属性,当类的定义,而不是当它被实例被创建。
比较:
class Foo(object):
def __init__(self):
self.a = {}
print self.a
self.filla()
def filla(self):
for i in range(10):
self.a[str(i)] = i
答
任何变量得到_ 初始化 _方法将是一个 '局部变量' 设置。
class Foo(object):
def __init__(self):
self.a = 'local' #this is a local varable
>>> f = Foo()
>>> f.a
'local'
>>> Foo.a
AttributeError: type object 'Foo' has no attribute 'a'
任何变量以外的_ 初始化 _方法将是一个 '静态变量'。
class Foo(object):
a = 'static' #this is a static varable
def __init__(self):
#any code except 'set value to a'
>>> f = Foo()
>>> f.a
'static'
>>> Foo.a
'static'
如果你想定义 '局部变量' 和 '静态变量'
class Foo(object):
a = 'static' #this is a static varable
def __init__(self):
self.a = 'local' #this is a local variable
>>> f = Foo()
>>> f.a
'local'
>>> Foo.a
'static'
要访问的静态值内_ 初始化 _方法,采用自我。 _ 类_ .A
class Foo(object):
a = 'static' #this is a static varable
def __init__(self):
self.a = 'local' #this is a local variable
self.__class__.a = 'new static' #access static value
>>> f = Foo()
>>> f.a
'local'
>>> Foo.a
'new static'
奇怪的,说实话,是每个人都认为这种行为违反直觉的,只是因为它不是在Java中发生的事情,C++,C#等。实际上,Python的行为是非常合情合理的,而替代行为很奇怪。在Python中,在class中声明的所有东西都是类的一部分,而函数(方法)是类的一部分(可能间接连接到对象以使多态性起作用),而数据成员(字段)是每个构造的一部分对象除非另有标记。 – 2012-03-15 03:25:08