我一直在尝试制作一个文本RPG,并开始开发库存系统。
这是我的代码:
class items(object):
def __init__(self, name, value, quantity=1):
self.name=name
self.raw=name.strip().lower()
self.quantity=quantity
self.value=value
self.net_value=quantity*value
def recalculate(self):
self.net_value=self.quantity*self.value
class Container(object):
def __init__(self, name, max_space):
self.name=name
self.inside={}
self.max_space=max_space
def __iter__(self):
return len(self.inside.items())
def __len__(self):
return len(self.inside)
def __contains__(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() instead.')
if item in self:
self[item].quantity+=quantity
self[item].recalculate()
else:
self[item]=item
def remove(self, item, quantity=1):
if item not in self:
raise KeyError('Item 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()
backpack=Container('Backpack', 15)
sword=items('Sword', 10)
gold=items('Gold Coin', 1, 50)
potion=items('Potion', 5)
backpack.add(sword)
backpack.add(gold)
for name, item in backpack:
print(item.name, item.quantity)
它给了我这个错误:
Traceback (most recent call last):
File "F:/2XK_/Coding/Python/Python_Battle/Maybe usefull/inv_2.py", line 72, in <module>
for name, items in backpack:
TypeError: iter() returned non-iterator of type 'int'
问题出在这一行for name, item in backpack:
(显然(。
我想打印的是:
Gold Coin 50
Sword 1
那么我该如何解决这个问题呢?如有任何帮助,我们将不胜感激。
您对"iter"的重新定义是错误的,应该这样做:
def __iter__(self):
yield from self.inside.items()