1 classCompany :2 def __init__(Self, name, staffs=[]):#There is no incoming list when the entity object is instantiated, causing the entity object to share the same default list object3Self.name =name4Self.staffs =Staffs5 6 defAdd (Self, staff_name):7 self.staffs.append (staff_name)8 9 defRemove (self, staff_name):Ten Self.staffs.remove (staff_name) One A if __name__=="__main__": -COM1 = Company ("COM1", ["test1","test2"]) -Com1.add ("test3") theCom1.remove ("test1") - Print("COM1 Value:", com1.staffs) - - #COM2 and COM3 did not pass in the list object, using the default value as the list object +COM2 = Company ("COM2") -Com2.add ("test2") + Print("COM2 Value:", com2.staffs) A atCOM3 = Company ("COM3") -Com3.add ("test3") - Print("COM2 Value:", com2.staffs) - Print("COM3 Value:", com3.staffs) - - #Print class default values in Print("class Default value:", company.__init__.__defaults__) - #determine if the same object to Print("whether the COM2 value and the COM3 value are the same object:", com2.staffs iscom3.staffs)
Output:
COM1 Value: ['test2','test3']com2 value: ['test2']com2 value: ['test2','test3']com3 value: ['test2','test3'] Class Default value: (['test2','test3'],) whether the COM2 value and the COM3 value are the same object: True
A classic parameter error in Python