Python 为什么要记住类属性?

Python 为什么要记住类属性?,python,class,Python,Class,下面是一个示例python模块: # 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 (

下面是一个示例python模块:

# 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

\u init\u方法中设置的任何变量都将是“局部变量”

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'
\u init\u方法之外的任何变量都将是“静态变量”

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'
使用self.\u class.访问\u init.方法中的静态值

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'

老实说,奇怪的是,每个人都觉得这种行为违反直觉,因为这不是爪哇、C++、C等人所发生的事情。实际上,Python的行为是完全有意义的,而且这种行为是奇怪的。在Python中,
中声明的所有内容都是类的一部分,而函数(方法)是类的一部分(可能间接连接到对象以使多态性工作),而数据成员(字段)是每个构造对象的一部分,除非另有标记。