So when I create a class similar to the one below I get unexpected behavior where it appears as if the instances of the beverage class are sharing the "stock" variable, but since the stock variable is declared in the init declaration, I thought it should be limited to an instance.
class Beverage():
def __init__(self, owner, beverages=[]):
self.stock = beverages
self.owner = owner
def add_drink(self, beverage):
self.stock.append(beverage)
def get_drink(self, beverage):
if beverage in self.stock:
print "(%s) Has beverage (%s)!" %(self.owner,beverage)
self.stock.remove(beverage)
else:
print "(%s) Does not have beverage (%s)!" %(self.owner,beverage)
her = Beverage("her",["milkshake"])
me = Beverage("I")
you = Beverage("You")
you.add_drink("milkshake")
you.add_drink("punch")
her.get_drink("milkshake")
me.get_drink("milkshake")
me.add_drink("tea")
you.get_drink("milkshake")
Output
(her) Has beverage (milkshake)!
(I) Has beverage (milkshake)!
(You) Does not have beverage (milkshake)!
The output appears to me that it should be:
(her) Has beverage (milkshake)!
(I) Does not have beverage (milkshake)!
(You) has beverage (milkshake)!
Since "you" and "her" added the beverage "milkshake" to their stocks, yet somehow "me" is able to access it as if it is a shared variable. When searching for similar posts on StackOverflow, I turned up a bunch of similar ones in which the coder had defined the variables on the class level, so it made sense that they were shared, but here the stock variable is declared on an instance level so I assumed Python would treat it as instance specific. Any explanation of why the code behaves this way?