The following code describes what I mean:
class Demo(object):
def __init__(self, data=[]):
self.data = data
def add(self, item):
self.data.append(item)
def get_data(self):
return self.data
def clear(self):
self.__init__()
demo = Demo()
demo.add(1)
demo.add(2)
demo.clear()
print(demo.get_data())
I would expect it to print out []
. Surprisingly, it does not.
I have to rewrite the class to fix it:
class Demo2(object):
def __init__(self, data=[]):
self.init(data)
def init(self, data=[]):
self.data = data
def add(self, item):
self.data.append(item)
def get_data(self):
return self.data
def clear(self):
self.init()
demo = Demo2()
demo.add(1)
demo.add(2)
demo.clear()
print(demo.get_data())
It correctly prints out []
this time.
What is special of python class's __init__()
method? It appears as if its argument is cached.