0

I recently discovered a strange behavior with a simple situation.

class MyClass:
    def __init__(self, data=[]):
        self.data = data

    def add(self, data):
        self.data.append(data)
    
    def see(self):
        return self.data

r = MyClass()
r.add("nice item")
print(r.see())

u = MyClass()
print(u.see())

Running this script returned this

['nice item']
['nice item']

How is that possible ? I assume r and u are different instance of MyClass but u return data added into r. Anybody can explain ?

ob2
  • 101
  • 5
  • 1
    The default argument `data` to the constructor method is mutable - if you're using an IDE like Pycharm, it similarly also complains and warns you that unexpected results like this can occur. – rv.kvetch Oct 27 '21 at 00:04
  • 2
    The solution is to define the `__init__` as so: `def __init__(self, data=None): self.data = data or []`. This results in an expected result of `['nice item'] []`. – rv.kvetch Oct 27 '21 at 00:06
  • 1
    Yes, this is the workaround I made, thanks for your answer ! – ob2 Oct 27 '21 at 10:08

0 Answers0