1

I do not understand why the following piece of code produces the output it does:

class A:

    x = [0]
    y = 0

    def __init__(self):
        self.x.append(1)
        self.y += 1

a = A()        
print a.x, a.y

a = A()        
print a.x, a.y

The output is:

[0, 1] 1
[0, 1, 1] 1

What I would expect is:

[0, 1] 1
[0, 1] 1

Using Python 2.7.6.

Micha
  • 349
  • 3
  • 14
  • `x` and `y` are class variables, at least until `__init__` does `self.y += 1`, which sets the instance variable `y` to the class variable `y` plus one. – Colonel Thirty Two Oct 03 '14 at 17:39
  • It's treating `x` and `y` as static because you created them as class variables. If you want them to be instance variables, you need to create them inside `__init__`. – dano Oct 03 '14 at 17:40

1 Answers1

1

The class itself is an object. You can modify the properties of a class. Every instance derived afterwards inherits these modifications, or to be more correct (see comment of jsbueno) every instance-"variable"/identifier referencing the original object hast instantly the same value.

x and y are not instance-variables but class-variables. So ever invocation/instantiation of the Class modifies them in __init__.

To get real instance-variables you need them to define inside of the __init__ method.

The slightly different behaviour of x and y are results of the differet mutability of those variables. While the list identified by x is a mutable object, the number 0 isn't! Therefore while with append you also change the state of the object referenced by the class-variable this doesn't happen for y, because y is immutable. Instead you assign a new object to the (now) instance-identifier y.

That's also the reason, why it's not very accurate to speak of variables in python, but better of "identifier". You practically put a tag/stamp/name-shield on an object. But the coupling between identifier and referenced object is quite loose. You can reattach the tag as you want, without loosing the referenced object, if it's otherwise referenced.

SethMMorton
  • 45,752
  • 12
  • 65
  • 86
Don Question
  • 11,227
  • 5
  • 36
  • 54