標籤:導致 class span defaults st3 div 經典 init com
1 class Company: 2 def __init__(self, name, staffs=[]):#實體化對象時沒有傳入列表,導致實體物件共用同一預設列表對象 3 self.name = name 4 self.staffs = staffs 5 6 def add(self, staff_name): 7 self.staffs.append(staff_name) 8 9 def remove(self, staff_name):10 self.staffs.remove(staff_name)11 12 if __name__=="__main__":13 com1 = Company("com1", ["test1", "test2"])14 com1.add("test3")15 com1.remove("test1")16 print("com1值:",com1.staffs)17 18 #com2與com3沒有傳入列表對象,使用了預設值作為列表對象19 com2 = Company("com2")20 com2.add("test2")21 print("com2值:",com2.staffs)22 23 com3 = Company("com3")24 com3.add("test3")25 print("com2值:",com2.staffs)26 print("com3值:",com3.staffs)27 28 #列印類預設值29 print("類預設值:",Company.__init__.__defaults__)30 #判斷是否為同一對象31 print("com2值與com3值是否為同一對象:",com2.staffs is com3.staffs)
輸出:
com1值: [‘test2‘, ‘test3‘]com2值: [‘test2‘]com2值: [‘test2‘, ‘test3‘]com3值: [‘test2‘, ‘test3‘]類預設值: ([‘test2‘, ‘test3‘],)com2值與com3值是否為同一對象: True
Python中一個經典的參數錯誤