Possible Duplicate:
Python: Difference between class and instance attributes
I’m trying to get my head around OOP in Python and I’m a bit confused when it comes to declare variables within a class. Should I declare them inside of the __init__ procedure or outside it? What’s the difference?
The following code works just fine:
# Declaring variables within __init__
class MyClass:
def __init__(self):
country = ""
city = ""
def information(self):
print "Hi! I'm from %s, (%s)"%(self.city,self.country)
me = MyClass()
me.country = "Spain"
me.city = "Barcelona"
me.information()
But declaring the variables outside of the __init__ procedure also works:
# Declaring variables outside of __init__
class MyClass:
country = ""
city = ""
def information(self):
print "Hi! I'm from %s, (%s)"%(self.city,self.country)
me = MyClass()
me.country = "Spain"
me.city = "Barcelona"
me.information()
In your first example you are defining instance attributes. In the second, class attributes.
Class attributes are shared between all instances of that class, where as instance attributes are “owned” by that particular instance.
Difference by example
To understand the differences let’s use an example.
We’ll define a class with instance attributes:
And one with class attributes:
And a function that prints out information about one of these objects:
Let’s create 2
MyClassOneobjects and change one to be Milan, and give Milan “something”:When we call
information()on thefoo1andbar1we get the values you’d expect:However, if we were to do exactly the same thing, but using instances of
MyClassTwoyou’ll see that the class attributes are shared between instances.And then call
information()…So as you can see –
thingsis being shared between the instances.thingsis a reference to a list that each instance has access to. So if you append to things from any instance that same list will be seen by all other instances.The reason you don’t see this behaviour in the string variables is because you are actually assigning a new variable to an instance. In this case that reference is “owned” by the instance and not shared at the class level. To illustrate let’s assign a new list to things for
bar2:This results in: