Python creating new object of class contains values of older object [duplicate]

This question already has an answer here:

I have got a class with a list-variable and a function to append items to this list. I cannot append items directly, because I have to validate them:

class Foo:
    def __init__(self, elements=[]):
        self.elements = elements

    def append(self, element):
        self.elements.append(element)

If I instantiate an object of this class, add items and then create another new object, this object contains the items of the first object.

foo = Foo()
print foo.elements  # []
foo.append(element=4)
print foo.elements  # [4]
foo.append(element=7)
print foo.elements  # [4, 7]
bar = Foo()
print bar.elements  # [4, 7]

Can someone explain my, why this happens?

A possible solution for me could be this, but I don’t like it…

class Foo:
    def __init__(self, elements=None):
        if elements is None:
            self.elements = []
        else:
            self.elements = elements

    def append(self, element):
        self.elements.append(element)

Thanks for all answers!


Source: oop

Leave a Reply