1

我正在手机上编程。我创建了类角色来保存有关角色的所有信息,例如 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对不起代码墙!

4

1 回答 1

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

https://docs.python.org/3/tutorial/classes.html

于 2018-10-02T09:06:47.667 回答