0

Here is a strange behaviour I observed with list objects in Python classes.

class Test:
    val = []

    def __init__(self):
        self.val.append(42)

a = Test()
b = Test()
print b.val

The output of above program is [42,42] rather than the expected [42].

class Test:
    val = 0

    def __init__(self):
        self.val+=5

a = Test()
b = Test()
print b.val

In this case the output is 5 as expected.

Following the rule above program showed, this program should have given output 10. Or vice-versa, the above output should have been only [42].

If multiple objects of the same type are instantiated, how are the list type objects accessible in different objects? This completely defies my OOP concepts.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
psiyumm
  • 6,437
  • 3
  • 29
  • 50
  • 2
    Yoy may find the answer here: http://stackoverflow.com/a/8701644/2679935 – julienc Jun 01 '14 at 11:37
  • You are using class attributes instead of instance attributes. Class attributes are shared amongst all instances of a class. And since you create two instances `a` and `b`, `__init__` gets called twice, appending to the list twice. – Lukas Graf Jun 01 '14 at 11:38
  • @Lukas that doesn't explain why in the second example, `val` isn't incremented twice. – Tom Fenech Jun 01 '14 at 11:39
  • 1
    lists are mutable ints are not – Padraic Cunningham Jun 01 '14 at 11:40
  • @TomFenech because in the second example he doesn't modify `self.val` (since it's immutable), he re-assigns is as an instance attribute every time. – Lukas Graf Jun 01 '14 at 11:43

0 Answers0