The outcome is not what I expected. When guya(an object) gets his lemon(also object) from guyb, both of them had their lemons increased and then decreased by 1, from what it seems. But if you uncomment the only commented line from this program, I tried to assign guyc lemon’s count to 1000, but that only set everyone’s lemon.quantity to 1000. What’s going on?
My purpose of the getlemon, in class slasher, function was to decrease the quantity of the target’s lemon by 1, and increase the self quantity of lemon by 1, but that failed. What did I do wrong? And when I tried to assign guyc.lemon.quantity to 1, what happened?
class item():
def __init__(self, x = 0): self.quantity = x
def set_quantity(self, newquantity): self.quantity = newquantity
class slasher():
health = 10
lemon = item(10)
def getlemon(self, target):#target is the placeholder
target.lemon.quantity -= 1
self.lemon.quantity += 1
target.health -= 1
guya = slasher()
guyb = slasher()
guyc = slasher()
guya.getlemon(guyb)
#guyc.lemon.quantity = 1000
def printit():
print("guya's lemon count:", guya.lemon.quantity)
print("guyb's lemon count:", guyb.lemon.quantity)
print("guyc's lemon count:", guyc.lemon.quantity)
print("guyb's health:", guyb.health)
printit()
lemon = item(10)runs exactly once, when the class is defined. So no matter which instance – you will always access the same object.To avoid this, create the object in the constructor:
You might want to do the same for
health– however, it’s not necessary in this case since as soon as you assign something toobj.healthit will be set on the instance (numbers are immutable.)