attribute that is a list behave weirdly with inherited class

35 Views Asked by At

If you compile this python code, what output do you think you'll get?

class Parent:
    def __init__(o,ls = []):
        o.list_truc = ls

class Truc:
    def __init__(o):
        pass

class Child(Parent):
    def __init__(o):
        super().__init__()

obj1 = Child() 
obj1.list_truc.append(Truc())
obj2 = Child()
obj2.list_truc.append(Truc())

print(len(obj2.list_truc))

! the answer is 2. But how does that makes sense? can someone explain this to me? obj2.list_truc is supposed to be empty at creation right? But it isn't. Also, changing the 3rd line to : o.list_truc = [] change something which is incomprehensible to me

0

There are 0 best solutions below