2016-04-29 42 views
-1
class Character(object): 

    def __init__(self): 
     self.name = "" 
     self.inventory = [] 

    def add_inventory(self, item): 
     self.inventory.append(item) 

    def view_inventory(self): 
     for i in range(len(self.inventory)): 
      print "%r. %s" % (i+1, self.inventory[i]) 


class Hero(Character): 

    def __init__(self): 
     self.name = "" 
     self.inventory = ["Torch", "Wrench", "Laser Cannon"] 

Hero().view_inventory() 
Hero().add_inventory("Key") 
Hero().view_inventory() 

我已經追加到它與add_inventory功能,顯示「鑰匙」作爲加入結束後測試的庫存情況的庫存清單,但是Hero()。view_inventory()打印出相同的結果,不包含Key。當我運行追加到列表後view_inventory功能,附項目不顯示

+1

你在那裏有3個不同的'英雄'實例。 – vaultah

回答

0

正如vaultah在評論中指出的那樣,您正在創建三個單獨的Hero實例。更改如下:

hero = Hero() # create one Hero instance 
hero.view_inventory() # and make the method calls on this very instance 
hero.add_inventory("Key") 
hero.view_inventory() 
相關問題