在列表中添加/移除项目
我正在尝试创建一个玩家,可以在他们的背包里添加和删除物品。我已经把大部分功能都搞定了,只是遇到了一个小问题。每次打印背包的时候,都会出现一个'None'。我一直在尝试去掉它,但无论我怎么做,'None'总是出现在程序里!我知道我只是漏掉了什么简单的东西,但我就是搞不明白。
class Player(object):
def __init__(self, name, max_items, items):
self.name=name
self.max_items=max_items
self.items=items
def inventory(self):
for item in self.items:
print item
def take(self, new_item):
if len(self.items)<self.max_items:
self.items.append(new_item)
else:
print "You can't carry any more items!"
def drop(self, old_item):
if old_item in self.items:
self.items.remove(old_item)
else:
print "You don't have that item."
def main():
player=Player("Jimmy", 5, ['sword', 'shield', 'ax'])
print "Max items:", player.max_items
print "Inventory:", player.inventory()
choice=None
while choice!="0":
print \
"""
Inventory Man
0 - Quit
1 - Add an item to inventory
2 - Remove an item from inventory
"""
choice=raw_input("Choice: ")
print
if choice=="0":
print "Good-bye."
elif choice=="1":
new_item=raw_input("What item would you like to add to your inventory?")
player.take(new_item)
print "Inventory:", player.inventory()
elif choice=="2":
old_item=raw_input("What item would you like to remove from your inventory?")
player.drop(old_item)
print "Inventory:", player.inventory()
else:
print "\nSorry, but", choice, "isn't a valid choice."
main()
raw_input("Press enter to exit.")
2 个回答
0
你能把这个函数替换成下面这个吗:
def inventory(self):
for item in self.items:
print item
然后再调用:
def inventory(self):
print self.items
或者你也可以使用这个函数:
print "Inventory"
player.inventory()
:
def print_inventory(self):
print "Inventory:"
for item in self.items:
print item
4
问题出在这句话上:
print "Inventory:", player.inventory()
你让Python打印从player.inventory()得到的值。但是你的inventory()方法只是打印库存内容,并没有返回任何东西,所以它的返回值实际上是None。
你可能想要明确选择以下两种方式之一:
print "Inventory:"
player.print_inventory()
或者你也可以让它返回一个字符串,然后这样做:
print "Inventory:", player.inventory_as_str()