我正在用手机编程。 我创建了类角色来保存有关该角色的所有信息,例如Hp。 定义了hp之后,我创建了一个名为getHp()的函数,该函数返回hp。 稍后,当我在“ stats()”函数中调用“ getHp()”时,它说未定义“ getHp()”。它对我课堂上的所有功能都相同。 只是“ stats()”只是一个函数,用于收集我所有的变量(在类内)并打印它们。
#Adventure game
import random, time
#===========================#
class character():
self.xp = 0
def getLvl(self, xp):
if xp < 5:
level = 1
elif xp < 20:
level = 2
elif xp < 60:
level = 3
elif xp < 120:
level = 4
else:
level = 5
return level
self.level = getLvl(self, xp)
#-----------------------------------------#
self.inventory = {"knife": 1 , "bread": 2 , "gold": 10}
self.armor = 0
#-----------------------------------------#
self.attack = 6
def getAttack(self, attack):
return attack
#-----------------------------------------#
self.dmg = 1
def getDmg(self, dmg):
return dmg
#-----------------------------------------#
self.hp = 10 * level + armor
def getHp(self, hp):
return hp
def updateHp(self, playerHp):
self.hp = playerHp
#-----------------------------------------#
def stats(self):
self.getLvl(xp)
self.getHp(hp)
self.getAttack(attack)
self.getDmg(dmg)
print("Player: \n")
print("Hp: ", hp, "\nLvl: ", level, "\nAttack: ", attack, "\nDmg: ", dmg)
print("Inventory: ", self.inventory)
#===========================#
character.stats()
P.s。抱歉,没有代码!
答案 0 :(得分:2)
When you are calling the functions within the class, are you using "self"? In your stats() method it should look like this:
def stats(self):
self.getHp()
This is a way that python knows to refer to the getHp() within the class.
You can find more on Classes and self in the python documentations