使用类中的return语句从类中获取值

时间:2017-09-05 14:31:35

标签: python pycharm

class Player1:
    base_HP = 300

    def getBHP(self):
        return self.base_HP


jogador1 = Player1
jogador1_hp = jogador1.getBHP() #Functions and Class calls must end with brackets.


print(jogador1_hp)

这是我用来获取播放器HP的代码,我想将其保存在jogador1_hp。

这是怎么回事:

C:\Users\joaol\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/joaol/PycharmProjects/FirstProgram/Main.py
<function Player1.getBHP at 0x02C131E0>

Process finished with exit code 0

即使我如下所示,我仍然得到一个空白的控制台。

class Player1:
    base_HP = 300

    def getBHP(self):
        print(self.base_HP)


jogador1 = Player1
jogador1.getBHP
编辑:我解决了,我只需要添加&#34;()&#34;当我创建对象时!

jogador1 = Player1()
jogador1_hp = jogador1.getBHP()

3 个答案:

答案 0 :(得分:3)

你必须调用它们的执行方法。

jogador1_hp = jogador1.getBHP()

答案 1 :(得分:0)

如果我使用jogador1_hp = jogador1.getBHP()我得到这个:

C:\Users\joaol\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/joaol/PycharmProjects/FirstProgram/Main.py
Traceback (most recent call last):
  File "C:/Users/joaol/PycharmProjects/FirstProgram/Main.py", line 19, in <module>
    jogador1_hp = jogador1.getBHP()
TypeError: getBHP() missing 1 required positional argument: 'self'

Process finished with exit code 1

答案 2 :(得分:0)

您没有实例化Player1课程。在您的代码中,jogador1只是Player1类的另一个名称。您应该调用该类来实例化它,例如:jogador1 = Player1()