I have a question about inheritance in Python 2.7.
I have a two simple classes
class A():
l = []
def f(self):
del self.l[:]
if self.a == 'a':
self.l.append('1')
if self.a == 'b':
self.l.append('2')
class B(A):
def __init__(self, a):
self.a = a
I create two instances of B in loop and call f() for set list 'l'
foo = ['a','b']
l = []
for x in foo:
z = B(x)
z.f()
# normal result
print z.l
l.append(z)
print '-----'
for x in l:
# strange result
print x.l
In result I get strange output:
Output:
['1']
['2']
-----
['2']
['2']
[Finished in 0.0s]
Instead 1,2; 1,2
Why is this happening?
I can fix it by define list "l" in def f(self)
class A():
def f(self):
l = []
if self.a == 'a':
self.l.append('1')
if self.a == 'b':
self.l.append('2')
In this case I get normal output, but still don't understand why this happens.
Thanks