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?

2
  • 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.) Commented May 1, 2012 at 4:06
  • They're called class variables. stackoverflow.com/questions/2714573/… or stackoverflow.com/questions/68645/… Commented May 1, 2012 at 4:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

3 Comments

I think class attribute and instance attribute are more appropriate terms.
Im not sure what you're trying to show with those bits of code, as they're exactly identical..
For anyone wondering, the first print statement will return True and the second will return False

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.