Reputation: 1
class GameCharacter(object):
def __init__(self, name, health=100,strength=10,inventory=[]):
self.name=name
self.health=health
self.strength=strength
self.inventory=inventory
def fight(self,other):
damage=random.randint(1,self.strength)
print(self.name+" hits "+other.name+", doing "+str(damage)+" damage.")
other.health-=damage
print(other.name+ " has "+str(other.health)+" health left\n")
def addToInventory(self, itemName):
self.itemName=itemName
self.inventory.append(itemName)
def checkInventory(self):
print(self.name + "'s inventory includes: " + str(self.inventory))
def __str__(self):
return self.name+"\n"+"Health: "+str(self.health)+"\n"+"Strength: "+str(self.strength)+"\n"+"Inventory: "+"\n"+str("\n".join(self.inventory))+"\n"
So I'm fairly new to programming in general, and for the life of me I can't figure out what I'm doing incorrectly. I'm working on an assignment that involves mock video game characters. I'm trying to add an "add to inventory" method and while it works, it apparently updates the entire class. So after Object #1 calls the method, future objects are retaining the same inventory as Object #1. I just want new objects to have an empty list for an inventory when they're created, which is how I have it set in the constructor.
Drew
Health: 105
Strength: 15
Inventory:
Rusty Sword
Weak Shield
Heavy Stick
<class '__main__.GameCharacter'>
<class 'list'>
Drew's inventory includes: ['Rusty Sword', 'Weak Shield', 'Heavy Stick']
Mister Pickle
Health: 100
Strength: 10
Inventory:
Rusty Sword
Weak Shield
Heavy Stick
Here is the output, where "Drew" is Object 1. "Mister Pickle" is a brand new object being printed. The name, health, and strength attributes are as intended. However, as you can see, Mister Pickle has the same inventory despite being a brand new object using the default constructor that should create a new, blank inventory as a list. Could someone please point me in the right direction? Thank you! And please ignore my goofy names, lol.
Upvotes: 0
Views: 145
Reputation: 36390
You encountered mutable default argument gotcha (it does also apply to functions, not only classes' methods), to prevent that avoid using mutable default argument, in your case change
def __init__(self, name, health=100,strength=10,inventory=[]):
self.name=name
self.health=health
self.strength=strength
self.inventory=inventory
to
def __init__(self, name, health=100,strength=10,inventory=None):
self.name=name
self.health=health
self.strength=strength
self.inventory=[] if inventory is None else inventory
Upvotes: 2