Python 错误:缺少 1 个必需的位置参数:'self'

Lia*_*yes 5 python class self

我是 Python 新手,我正在尝试学习如何使用类。有谁知道为什么这不起作用?任何有关关键字“self”的其他提示将不胜感激。

代码:

class Enemy:
    life = 3

    def attack(self):
        print('ouch!')
        self.life -= 1

    def checkLife(self):
        if self.life <= 0:
            print('I am dead')
        else:
            print(str(self.life) + "life left")


enemy1 = Enemy
enemy1.attack()
enemy1.checkLife()
Run Code Online (Sandbox Code Playgroud)

错误:

C:\Users\Liam\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Liam/PycharmProjects/YouTube/first.py
Traceback (most recent call last):
  File "C:/Users/Liam/PycharmProjects/YouTube/first.py", line 16, in <module>
    enemy1.attack()
TypeError: attack() missing 1 required positional argument: 'self'

Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

zai*_*zil 7

Enemy是班级。Enemy()是该类的一个实例Enemy。您需要初始化该类,

enemy1 = Enemy()
enemy1.attack()
enemy1.checkLife()
Run Code Online (Sandbox Code Playgroud)