I was working on a simple script today when I noticed a strange quirk in the way 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 like the "eggs" dictionary is shared between all the different "Spam" instances -- either that or it is overwritten every time a new instance is created. This isn't really a problem in every day life, since we can solve it by declaring the 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
With the code written this way, the result is what we expect:
My favorite type of bacon is Canadian bacon
My favorite type of bacon is American bacon
So while I'm not held up by this behavior, I don't understand why Python works this way. Can anyone shed some light on this?