0

Why this code:

class B:
    val = []

for i in range(0, 5):
    obj = B()
    print(obj.val)
    obj.val.append('a')

has such output?

[]
['a']
['a', 'a']
['a', 'a', 'a']
['a', 'a', 'a', 'a']

In each iteration new B object is created. Why it has value of previous one?

Seagull
  • 3,319
  • 2
  • 31
  • 37

2 Answers2

6

You're modifying a class attribute not instance attribute. Change val to an instance attribute:

class B(object):
    def __init__(self):
        self.val = []
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

You have provided example of how to use static variables in python. Answer to question "Static class variables in Python" explains how to achieve what you have done. It looks like every coin has two sides.

Python Programming FAQ explains such behaviour in detail: http://docs.python.org/2/faq/programming.html#how-do-i-create-static-class-data-and-static-class-methods

Community
  • 1
  • 1
iljau
  • 2,151
  • 3
  • 22
  • 45