I'm not sure if this is a fundamental misunderstanding on my part of the way that OOP in Python works, but I'm seeing some extremely strange behavior. Here's a code snippet:
class Foo(object):
def __init__(self, l = []):
print "Foo1:", l
self.mylist = l
print "Foo2:", self.mylist
class Bar(Foo):
def __init__(self, label=None):
self.label = label
super(Bar, self).__init__()
print "Bar:", self.mylist
bar1 = Bar()
bar1.mylist.append(4)
bar2 = Bar()
print "bar2's list:", bar2.mylist
I expect that when bar2
is constructed, its mylist
instance variable will be set to the empty list. However, when I run this program in Python 2.6.6, I get the following output:
Foo1: []
Foo2: []
Bar: []
Foo1: [4]
Foo2: [4]
Bar: [4]
bar2's list: [4]
It looks like Foo's mylist instance variable is being persisted across multiple instances of the Bar class, but I have no idea why that would be. Any help you guys could give me would be greatly appreciated.