Python错误:缺少1个需要的位置参数:'self'
问题描述:
我是Python新手,我试图学习如何使用类。有谁知道这是怎么回事?任何关于关键字“自我”的额外提示将不胜感激。Python错误:缺少1个需要的位置参数:'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>
fuck.attack()
TypeError: attack() missing 1 required positional argument: 'self'
Process finished with exit code 1
答
Enemy
是类。 Enemy()
是类Enemy
的一个实例。 你需要初始化这个类,
enemy1 = Enemy()
enemy1.attack()
enemy1.checkLife()
'enemy1 = Enemy'不是怎么实例化和'Enemy'对象。你刚刚将'Enemy'类分配给变量'enemy1'。 –
'Enemy'是班级。 'Enemy()'是这个类的一个新实例。将'enemy1'设置为后者。 – Ryan
https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/ – Rosh