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