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.
It's an attribute of the class, not the instance, and is created when the class is defined, not when it is instantiated.
Compare:
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:Any variable get set in _init_ method will be a 'local variable'.
Any variable outside of _init_ method will be a 'static variable'.
If you want define 'local variable' and 'static variable'
To access static value inside _init_ method, using self._class_.a