It's really like "What?"
Code in question
# -*- coding: utf-8 -*-
class Hoge():
def __init__(self, data=[]):
self.data = data
def add_data(self):
self.data.append(u"ʅ(´◔౪◔)ʃ")
if __name__ == "__main__":
hoge = Hoge()
hoge.add_data()
hoge2 = Hoge()
print hoge2.data[0]
When executed, ʅ (´◔౪◔) ʃ
will be displayed.
???????
If you do the following, data will not be inherited by hoge2
# -*- coding: utf-8 -*-
class Hoge():
def __init__(self):
self.data = []
def add_data(self):
self.data.append(u"ʅ(´◔౪◔)ʃ")
if __name__ == "__main__":
hoge = Hoge()
hoge.add_data()
hoge2 = Hoge()
print hoge2.data
Furthermore, if you put a string instead of a list, it will not be inherited even if you put an argument in the constructor
# -*- coding: utf-8 -*-
class Hoge():
def __init__(self, data=''):
self.data = data
def add_data(self):
self.data = u"ʅ(´◔౪◔)ʃ"
if __name__ == "__main__":
hoge = Hoge()
hoge.add_data()
hoge2 = Hoge()
print hoge2.data
Why... Why inherits instance variables when you put the default value in the argument of the constructor?
I don't know the cause, but be careful. If you know the cause, I would appreciate it if you could comment.
Recommended Posts