我今天正在编写一个简单的脚本,当时我注意到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"]
Run Code Online (Sandbox Code Playgroud)
我们使用单独的参数创建此对象的两个实例:
spam1 = Spam("Canadian bacon")
spam2 = Spam("American bacon")
print spam1
print spam2
Run Code Online (Sandbox Code Playgroud)
结果令人费解:
My favorite type of bacon is American bacon
My favorite type of bacon is American bacon
Run Code Online (Sandbox Code Playgroud)
似乎所有不同的"垃圾邮件"实例之间共享"蛋"字典 - 无论是每次创建新实例还是覆盖它.这在日常生活中并不是真正的问题,因为我们可以通过在初始化函数中声明实例变量来解决它:
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 " + …Run Code Online (Sandbox Code Playgroud)