I was working on a simple script today when I noticed a strange quirk about how Python treats instance variables.
Say we have a simple object:
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"]
And we create two instances of this object with separate arguments:
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
It seems that the dictionary of eggs is shared between all different copies of Spam - either this or is overwritten each time a new instance is created. This is not a problem in everyday life, since we can solve it by declaring an instance variable in the initialization function:
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
When writing code in this way, the result will be what we expect:
My favorite type of bacon is Canadian bacon My favorite type of bacon is American bacon
Therefore, although I do not support this behavior, I do not understand why Python works this way. Can anyone shed some light on this?
source share