I'm trying to simulate an inventory, and the debugger isn't finding anything wrong, except
when I run the file to test it, it prints false to an item being added even though it should print true. It's not informing me that there is an error in the code, so I do not know where to look. If you could tell me what I need to change so it will return true at the end (print(sword in bag)
) that would be a big help. Ty.
class Item(object):
def __init__(self, name, value, quantity=1):
self.name = name
self.raw = name.strip().lower()
self.quantity = quantity
self.value = value
self.netValue = quantity * value
def recalc(self):
self.netValue = self.quantity * self.value
class Container(object):
def __init__(self, name):
self.name = name
self.inside = {}
def __iter__(self):
return iter(list(self.inside.items()))
def __len__(self):
return len(self.inside)
def __containts__(self, item):
return item.raw in self.inside
def __getitem__(self, item):
return self.inside[item.raw]
def __setitem__(self, item, value):
self.inside[item.raw] = value
return self[item]
def add(self, item, quantity=1):
if quantity < 0:
raise ValueError("Negative Quantity, use remove()")
if item in self:
self[item].quantity += quantity
self[item].recalc()
else:
self[item] = item
def remove(self, item, quantity=1):
if item not in self:
raise KeyError("Not in container")
if quantity < 0:
raise ValueError("Negative quantity, use add() instead")
if self[item].quantity <= quantity:
del self.inside[item.raw]
else:
self[item].quantity -= quantity
self.item.recalc()
bag = Container("BagOfHolding")
sword = Item("Sword", 10) potion = Item("Potion", 5) gold = Item("Gold coin", 1, 50)
bag.add(sword)
print(sword in bag) print(potion in bag)
it looks like you misspelled __contains__
in your method definition.