【发布时间】: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