我今天正在用简单的文字做工作,当时我注意到在山谷处理场变量方面存在着奇怪的qui。
我们有一个简单的目标:
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
The results are puzzling:
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
因此,虽然我不听从这一行为,但我不理解为什么斯图尔这样做。 谁能对此有所了解?