0

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!

be-ndee
  • 1,153
  • 3
  • 13
  • 19

1 Answers1

1

You've got your answer yourself already. Initializing with a mutable object ist never a good idea. It will be initialized once the class gets defined and reused for every instance.

knitti
  • 6,817
  • 31
  • 42