добавить / удалить элементы в списке - PullRequest
4 голосов
/ 23 марта 2010

Я пытаюсь создать игрока, который может добавлять и удалять предметы из своего инвентаря. У меня все работает, у меня просто 1 маленькая проблема. Каждый раз, когда он печатает инвентарь, также появляется сообщение «Нет». Я возился с этим, чтобы попытаться удалить это, но независимо от того, что я делаю, в программе всегда появляется «Нет»! Я знаю, что просто упускаю что-то простое, но я не могу понять это ради своей жизни.

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 ]

4 голосов
/ 23 марта 2010

Проблема заключается в следующем:

print "Inventory:", player.inventory()

Вы говорите Python напечатать значение, возвращаемое из player.inventory ().Но ваш метод инвентаризации () просто печатает инвентарь, он ничего не возвращает, поэтому возвращаемое значение неявно Нет.

Вы, вероятно, хотите явно выбрать либо:

print "Inventory:"
player.print_inventory()

Или же вы можете вернуть строку и сделать следующее:

print "Inventory:", player.inventory_as_str()
0 голосов
/ 23 марта 2010

Не могли бы вы заменить функцию:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...