【发布时间】:2012-02-10 05:44:48
【问题描述】:
今天我正在编写一个简单的脚本时,我注意到 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
似乎“eggs”字典在所有不同的“垃圾邮件”实例之间共享 - 或者每次创建新实例时都会覆盖它。这在日常生活中并不是真正的问题,因为我们可以通过在初始化函数中声明实例变量来解决它:
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 为什么会这样工作。任何人都可以对此有所了解吗?
【问题讨论】: