I just wonder, why variable defined by __init__ is not accessible from class? Should its executed during instantiation, so that its accessible from outside?
>>> class a:
... data = {}
...
>>> a.data
{}
>>> class a:
... def __init__(self):
... self.data = {}
...
>>> a.data
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class a has no attribute 'data'
Variables defined in
__init__are instance variables, by definition they can’t be accessed from a class scope. That’s why this works:… Whereas this won’t work:
Notice that
__init__(the initializer) is run when you create a new instance ofaby callinga(), from that point on all the variables defined in__init__are bound to that particular instance ofa.