Why class attribute is remembered?

て烟熏妆下的殇ゞ 提交于 2020-01-05 02:47:27

问题


Here is a sample python module:

# 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

then I do this in 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}

Why the second time a is not empty? Am I missing something trivial.


回答1:


The problem is that a is not bound. It is a property of the class, not the object. You want to do something like this:

# 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



回答2:


It's an attribute of the class, not the instance, and is created when the class is defined, not when it is instantiated.

Compare:

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



回答3:


Any variable get set in _init_ method will be a 'local variable'.

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'

Any variable outside of _init_ method will be a 'static variable'.

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'

If you want define 'local variable' and 'static variable'

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'

To access static value inside _init_ method, using self._class_.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'


来源:https://stackoverflow.com/questions/9713259/why-class-attribute-is-remembered

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!