python的形参为可变数据类型的坑
------------恢复内容开始---------
函数可能会修改接收到的任何可变对象。不要使用可变类型的参数作为函数的参数默认值。
class Bus: def __init__(self, passengers=[]): self.passengers = passengers def pick(self, name): self.passengers.append(name) def drop(self, name): self.passengers.remove(name) bus1 = Bus(['a', 'b']) print(bus1.passengers) bus1.pick('c') bus1.drop('a') print(bus1.passengers) bus2 = Bus() bus2.pick('a') print(bus2.passengers) bus3 = Bus() bus3.pick('b') print(bus3.passengers) print(bus2.passengers) ['a', 'b'] ['b', 'c'] ['a'] ['a', 'b'] ['a', 'b']
# 浅复制的实际用处:保障篮球队的名单不变 basketball_team = ['a', 'b', 'c'] class TwilightBus: def __init__(self, passengers=None): if passengers is None: self.passengers = [] else: self.passengers = list(passengers) def drop(self, name): self.passengers.remove(name) bus1 = TwilightBus(basketball_team) bus1.drop('a') bus1.drop('b') print(basketball_team)#['a', 'b', 'c']
-