Python语言陷阱总结
默认参数的问题:
class Foo:
def __init__(self, data=[]):
self.data = data # 创建Foo的实例时,若是省略data参数,则所有创建的对象将会共享同一个data列表,汗!!!
print("self: %s, data: %s" % (id(self), id(self.data)))
@classmethod
def create(cls, n):
foo = cls() # Workaround: foo = cls([]),不让它使用默认参数
foo.data.append(n)
return foo
a = Foo.create(123) # Output: "self: 28488224, data: 28311144"
b = Foo.create(456) # Output: "self: 28488248, data: 28311144"
print(a.data) # Output: "[123, 456]"
print(b.data) # Output: "[123, 456]"