I'm brand new to Python, and I'm trying to learn how to work with classes. Does anyone know how come this is not working? Any additional tips about the keyword "self" would be greatly appreciated.
The code:
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()
The error:
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
enemy1 = Enemy
is not how instantiate andEnemy
object. You've just assigned theEnemy
class to the variableenemy1
. – PugilistEnemy
is the class.Enemy()
is a new instance of the class. Setenemy1
to the latter. – Fugacious