I'm having a misunderstanding about python classes/variables when used in an array. Given the below example, I would expect each 'basket' to have only one 'apple'. Yet each one ends up with 5? Why is that and how can I fix my code?
class Apple:
def __init__(self):
return
class Basket:
apples: list[Apple] = list()
def add_apple(self, apple):
self.apples.append(apple)
baskets = list()
for i in range(5):
# I'm instantiating a new basket here, why do apples keep getting added to the 'old' baskets that are in the baskets array?
b = Basket()
a = Apple()
b.add_apple(a)
baskets.append(b)
for b in baskets:
print(len(b.apples))
applesis a class variable - it is shared by all instances of the Basket class. You need to define it inside__init__if you want each instance to have its own list. Relevant documentationapplesis initialized once when class is created (class, not instance). So allBasketinstances share the sameappleslist (because it's mutable). To fix this behavior, move this initialization code into__init__method, it will makeapplesan instance attribute instead.assert baskets[0].apples is baskets[1].apples- it will not throw, so the list instances are exactly the same and all attributes point to the same object.