python - Error when using classes and then calling on the class
问题描述
I made a class as you can see here.
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
But then when I try and call on the healing_potions part like so
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
Then it gives me this error
Traceback (most recent call last): File "c:/Users/Isaiah/Desktop/All of my programs/Role playing game.py", line 179, in healing_potions += 1 NameError: name 'healing_potions' is not defined PS C:\Users\Isaiah\Desktop\All of my programs>
解决方案
我不太明白你为什么在你的播放器类中初始化一个播放器对象。这会导致无限递归,您会不断地无限地创建玩家实例。您很可能需要在课堂之外创建它。我在类中添加了一个方法,因此我们可以使用属于该实例的方法来增加健康药水。这通常是推荐的做法。
#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
您必须参考您想要增加健康药水的玩家。