繁体   English   中英

添加/删除列表中的项目

[英]add/remove items in a list

我正在尝试创建一个可以添加和删除其库存中的商品的玩家。 我有一切工作,我只有一个小问题。 每次打印清单时,也会显示“无”。 我一直在搞乱它试图删除它,但不管我做什么,“无”总是出现在程序中! 我知道我只是错过了一些简单的事情,但我无法理解我的生活。

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.")

问题是这句话:

print "Inventory:", player.inventory()

你告诉Python打印从player.inventory()返回的值。 但是您的inventory()方法只打印库存,它不返回任何内容 - 因此返回值隐式为None。

您可能希望明确选择以下内容:

print "Inventory:"
player.print_inventory()

或者你可以让它返回一个字符串并执行此操作:

print "Inventory:", player.inventory_as_str()

你介意更换功能吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM