gpt4 book ai didi

python - 使用类然后调用类时出错

转载 作者:行者123 更新时间:2023-12-01 06:34:32 25 4
gpt4 key购买 nike

我创建了一个类(class),正如您在此处看到的那样。

    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

然后它给了我这个错误

回溯(最近一次调用最后一次): 文件“c:/Users/Isaiah/Desktop/我的所有程序/角色扮演游戏.py”,第 179 行,位于 治疗药水 += 1NameError:名称“healing_potions”未定义PS C:\Users\Isaiah\Desktop\我的所有程序>

最佳答案

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

#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

您必须引用您想要增加生命药水的玩家。

关于python - 使用类然后调用类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59738872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com