In the first example, you define the attributes of an instance. The second is class attributes.
Class attributes are shared between all instances of this class, where this particular instance "belongs" as instance attributes.
Difference by example
To understand the differences, use an example.
We will define a class with instance attributes:
class MyClassOne: def __init__(self): self.country = "Spain" self.city = "Barcelona" self.things = []
And one with class attributes:
class MyClassTwo: country = "Spain" city = "Barcelona" things = []
And a function that displays information about one of these objects:
def information(obj): print "I'm from {0}, ({1}). I own: {2}".format( obj.city, obj.country, ','.join(obj.things))
Create 2 MyClassOne objects and change them to Milan and give Milan โsomethingโ:
foo1 = MyClassOne() bar1 = MyClassOne() foo1.city = "Milan" foo1.country = "Italy" foo1.things.append("Something")
When we call information() on foo1 and bar1 , we get the values โโyou expect:
>>> information(foo1) I'm from Milan, (Italy). I own: Something >>> information(bar1) I'm from Barcelona, (Spain). I own:
However, if we do the same, but using instances of MyClassTwo , you will see that class attributes are shared between instances.
foo2 = MyClassTwo() bar2 = MyClassTwo() foo2.city = "Milan" foo2.country = "Italy" foo2.things.append("Something")
And then call information() ...
>>> information(foo2) I'm from Milan, (Italy). I own: Something >>> information(bar2) I'm from Barcelona, (Spain). I own: Something
So, as you can see, things shared between instances. things - a link to a list to which each instance has access. Therefore, if you add to things from any instance, the same list will be displayed by all other instances.
The reason you don't see this behavior in string variables is because you are actually assigning a new variable to the instance. In this case, this reference "belongs" to the instance and is not used at the class level. To illustrate, assign a new list of things to bar2 :
bar2.things = []
This leads to:
>>> information(foo2) I'm from Milan, (Italy). I own: Something >>> information(bar2) I'm from Barcelona, (Spain). I own: