我是Python的新手,我正在尝试学习如何使用类。有人知道这怎么不起作用吗?关于关键字“自我”的任何其他提示将不胜感激。
编码:
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()
是该类的一个实例Enemy
。您需要初始化课程,
enemy1 = Enemy()
enemy1.attack()
enemy1.checkLife()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句