I'm building a Class in Python and I found an unexpected behavior. It's actually easy to solve, I just think I have a misconception about Python fundamentals and would like to understand what it is.
- Expected: All properties inside
__init__
should be exclusive to an object. - Actual Result: The second object somehow inherits properties from the first one.
- Goal: Understand my misconception about Python fundamentals.
The code is easily reproducible and self explanatory.
class MyClass:
def __init__(self, custom_list=[]):
self.object_list = custom_list
def add_to_list(self, item):
self.object_list.append(item)
p1 = MyClass()
print("p1 starts with empty list", p1.object_list) # [] ✅
p1.add_to_list("p1_item")
print("Now p1 list is populated:", p1.object_list) # ['p1_item'] ✅
p2 = MyClass()
print("p2 should start with empty list", p2.object_list) # ['p1_item'] ❌
This is one way to easily fix the issue (even though I don't understand why):
class MyClass:
def __init__(self, custom_list=[]):
if custom_list:
self.object_list = custom_list
else:
self.object_list = []
Lastly, it seems to affect a more complex object, like a list
or a dictionary
, but it won't affect a simple variable, like a float. Those code are analogous:
# ✅ This works fine
class MyFloat:
def __init__(self, a=0):
self.a = a
def increment_a(self, x):
self.a+=x
# ❌ This also fails
class MyDict:
def __init__(self, custom_dict={}):
self.object_list = custom_dict
def add_to_dict(self, item):
self.object_list.update(item)