python-3.x - 【暂时关闭】Python类定义未定义。错误
问题描述
我正在手机上编程。我创建了类角色来保存有关角色的所有信息,例如 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()
Ps对不起代码墙!
解决方案
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
推荐阅读
- eclipse - 我在哪里可以学习如何以编程方式将项目导入 Eclipse?
- java - 显示对象数组列表,在 TableView 的对象数组列表内
- gradle - Gradle jlink 选项给出访问权限警告
- sql - 使用循环 postgres 更新表数据
- list - 我需要存储为地理位置列表的道路数据
- r - ggplot2 中 PCA 分数的 Facetgrid
- python-3.x - 在 Tensorboard 中使用 Tensorflow v2.0 显示图形
- javascript - 页面未使用本地存储更新
- wordpress - add_filter() 中的函数永远不会运行
- python - 将值添加到序列化字典而不加载它