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.
The problem is that default parameters are bound at module initialization time, not at function invocation time, so there is only one default list that gets shared as the default for all invocations of that function.
What you really want to do is:
def __init__(self, l=None):
if l is None:
l = []
self.mylist = l
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With