Possible Duplicate:
Instance variables vs. class variables in Python
What is the difference between these two situations and how is it treated with in Python?
Ex1
class MyClass:
anArray = {}
Ex2
class MyClass:
__init__(self):
self.anArray = {}
It seems like the in the first example the array is being treated like a static variable. How does Python treat this and what is the reason for this?
In the first example,
anArray(which in Python is called a dictionary, not an array) is a class attribute. It can be accessed usingMyClass.anArray. It exists as soon as the class is defined.In the second example,
anArrayis an instance attribute. It can be accessed usingMyClass().anArray. (But note that doing that just throws away theMyClassinstance created; a more sensible example ismc = MyClass(); mc.anArray['a'] = 5.) It doesn’t exist until an instance of the class is created.