【问题标题】:Error when using classes and then calling on the class使用类然后调用类时出错
【发布时间】:2020-01-14 17:25:27
【问题描述】:

我做了一个课程,你可以在这里看到。

    class Player():
        def __init__(self, name, maxhealth, base_attack, gold, weapon, curweapon, healing_potions):
            player = Player('player', 100, 100, 5, 30, 'Normal Sword', 'Normal Sword', 0 )
            self.name = name
            self.maxhealth = maxhealth
            self.health = self.maxhealth
            self.base_attack = base_attack
            self.gold = gold
            self.weap = weapon
            self.curweapon = curweapon
            self.healing_potions = healing_potions

但是当我尝试像这样调用healing_potions部分时

                    if question == '2':
                        player_in_diningroom = True
                        print("You enter the dining room")
                        print("")
                        print("You find a Potion Of healing on the table!")
                        print("")
                        healing_potions += 1
                        player_in_diningroom = False

然后它给了我这个错误

Traceback(最近一次调用最后一次): 文件“c:/Users/Isaiah/Desktop/All of my programs/Role playing game.py”,第 179 行,在 治疗药水 += 1 NameError:未定义名称“healing_potions” PS C:\Users\Isaiah\Desktop\我的所有程序>

【问题讨论】:

  • 你的方法参数列表是否以self开头?您还没有指出您在哪里定义了代码。
  • self.healing_potions 如果函数在构造函数内部。否则它可能类似于 your_player_variable.healing_potion
  • 通常你只使用类中方法的实例字段。方法以 self 作为 Python 中的参数开头。
  • 你能给我一个我在这里的代码示例吗?
  • 所以当我调用healing_potions += 1 时,我会改为使用self.healing_potions += 1?

标签: python


【解决方案1】:

我不太明白你为什么在你的播放器类中初始化一个播放器对象。这会导致无限递归,您会不断地无限地创建玩家实例。 您很可能需要在课堂之外创建它。我在类中添加了一个方法,因此我们可以使用属于该实例的方法来增加健康药水。这通常是推荐的做法。

#player class
class Player():
    def __init__(self, name, maxhealth, base_attack, gold, weapon, curweapon, healing_potions):
        self.name = name
        self.maxhealth = maxhealth
        self.health = self.maxhealth
        self.base_attack = base_attack
        self.gold = gold
        self.weap = weapon
        self.curweapon = curweapon
        self.healing_potions = healing_potions
    def increase_health_potions(self):
        self.healing_potions +=1

然后我们初始化一个播放器实例/对象。我注意到您创建的实例中有一个额外的参数,所以我删除了一个以使其正常工作

#create an instance called player
player = Player('player', 100, 100, 5, 'Normal Sword', 'Normal Sword', 0 )

question = '2'
if question == '2':
    player_in_diningroom = True
    print("You enter the dining room")
    print("")
    print("You find a Potion Of healing on the table!")
    print("")
    player.healing_potions += 1 #accesing and increasing variable belonging to instance
    player.increase_health_potions() #call method belonging to instance that increases the variable 
    player_in_diningroom = False

print(player.healing_potions)

上通知
player.healing_potions += 1

你必须参考你想要增加生命药水的玩家。

【讨论】:

  • 非常感谢!完美运行!
猜你喜欢
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 2012-01-30
  • 2012-07-24
  • 1970-01-01
相关资源
最近更新 更多