Why Class Attribute Is Remembered?
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
Solution 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.pyclassFoo(object):
def__init__(self):
self.a = {}
print self.a
self.filla()
deffilla(self):
for i inrange(10):
self.a[str(i)] = i
Solution 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:
classFoo(object):
def__init__(self):
self.a = {}
print self.a
self.filla()
deffilla(self):
for i inrange(10):
self.a[str(i)] = i
Solution 3:
Any variable get set in _init_ method will be a 'local variable'.
classFoo(object):
def__init__(self):
self.a = 'local'#this is a local varable>>> f = Foo()
>>> f.a
'local'>>> Foo.a
AttributeError: typeobject'Foo' has no attribute 'a'
Any variable outside of _init_ method will be a 'static variable'.
classFoo(object):
a = 'static'#this is a static varabledef__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'
classFoo(object):
a = 'static'#this is a static varabledef__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
classFoo(object):
a = 'static'#this is a static varabledef__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'
Post a Comment for "Why Class Attribute Is Remembered?"