Python 使用类然后调用该类时出错
正如你在这里看到的,我上了一节课Python 使用类然后调用该类时出错,python,Python,正如你在这里看到的,我上了一节课 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
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
但是当我试着像这样调用治疗药剂的时候
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/All-of-my-programs/Role-playing game.py”,第179行,在
治疗药剂+=1
名称错误:未定义名称“治疗药剂”
PS C:\Users\Isaiah\Desktop\All my programs>我不太明白为什么要在player类中初始化player对象。这会导致无限重复,您不断无限地创建玩家实例。 您很可能需要在类之外创建它。我向类中添加了一个方法,这样我们就可以使用属于实例的方法来增加健康药水。这通常是推荐的做法
#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
你必须参考你想要增加生命药水的玩家。你的方法参数列表是从
self
开始的吗?如果函数在构造函数中,则未指明定义代码的位置。self.recovering\u potations
。否则它可能类似于您的\u player\u变量。通常,您只使用类内方法的实例字段。方法以Python中的self
作为参数开始。你能给我一个我这里的代码示例吗?所以当我调用治疗药剂+=1时,我会改为使用self.recovering药剂+=1?非常感谢!很好用!