今天我正在研究一个简单的脚本,当我注意到Python处理实例变量的方式时出现了一个奇怪的怪癖。为什么Python似乎将实例变量视为在对象之间共享?
说我们有一个简单的目标:
class Spam(object):
eggs = {}
def __init__(self, bacon_type):
self.eggs["bacon"] = bacon_type
def __str__(self):
return "My favorite type of bacon is " + self.eggs["bacon"]
我们创建这个对象有独立的参数的两个实例:
spam1 = Spam("Canadian bacon")
spam2 = Spam("American bacon")
print spam1
print spam2
结果令人费解:
My favorite type of bacon is American bacon
My favorite type of bacon is American bacon
它看起来像所有不同的“垃圾邮件”实例之间共享“蛋”字典 - 无论是它或它每次创建新实例时都会被覆盖。这是不是真的在日常生活中的一个问题,因为我们可以在初始化函数声明实例变量解决这个问题:
class Spam(object):
def __init__(self, bacon_type):
self.eggs = {}
self.eggs["bacon"] = bacon_type
def __str__(self):
return "My favorite type of bacon is " + self.eggs["bacon"]
spam1 = Spam("Canadian bacon")
spam2 = Spam("American bacon")
print spam1
print spam2
有了这样写的代码,结果是我们所期望的:
My favorite type of bacon is Canadian bacon
My favorite type of bacon is American bacon
所以,虽然我没有被这种行为所束缚,但我不明白为什么Python会以这种方式工作。任何人都可以对此有所了解吗?
可能的重复[如何避免在实例间共享Python类数据?](http://stackoverflow.com/questions/1680528/how-do-i-avoid-having-python-class-data-shared -among-instances) – 2013-02-23 15:26:10