1

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?

Community
  • 1
  • 1
Jordonias
  • 5,778
  • 2
  • 21
  • 32
  • It's not a "static variable", but it is a member of a *specific object* which that has a "stable name". Which object might that be? ;-) (Remember, classes are not "just definitions" in Python.) –  May 01 '12 at 04:06
  • They're called class variables. http://stackoverflow.com/questions/2714573/instance-variables-vs-class-variables-in-python or http://stackoverflow.com/questions/68645/static-class-variables-in-python – wkl May 01 '12 at 04:07

2 Answers2

5

In the first example, anArray (which in Python is called a dictionary, not an array) is a class attribute. It can be accessed using MyClass.anArray. It exists as soon as the class is defined.

In the second example, anArray is an instance attribute. It can be accessed using MyClass().anArray. (But note that doing that just throws away the MyClass instance created; a more sensible example is mc = MyClass(); mc.anArray['a'] = 5.) It doesn't exist until an instance of the class is created.

senderle
  • 145,869
  • 36
  • 209
  • 233
0

It is declared diffrent area. Ex1 is Like global or static variable.

obj = MyClass()
obj2 = MyClass()
print "IS one instance ", id(obj.anArray) == id(obj2.anArray)

Ex2 is local attribute.

obj = MyClass()
obj2 = MyClass()
print "IS one instance ", id(obj.anArray) == id(obj2.anArray)
Ankhaa
  • 1,128
  • 2
  • 12
  • 17
  • 1
    I think class attribute and instance attribute are more appropriate terms. – jdi May 01 '12 at 04:37
  • Im not sure what you're trying to show with those bits of code, as they're exactly identical.. – Joost Dec 24 '12 at 20:51
  • For anyone wondering, the first print statement will return True and the second will return False – Aswin Feb 24 '20 at 19:15