Skip to content Skip to sidebar Skip to footer

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.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

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:

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

Solution 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'

Post a Comment for "Why Class Attribute Is Remembered?"