我是一名新手学习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()
这个错误:
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
Enemy
对象的正确方式。你只是将Enemy
类赋值给了变量enemy1
。 - juanpa.arrivillagaEnemy
是一个类。Enemy()
是该类的一个新实例。将enemy1
设置为后者。 - Ry-