Search code examples
pythonclassself

Python error: missing 1 required positional argument: 'self'


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

Solution

  • Enemy is the class. Enemy() is an instance of the class Enemy. You need to initialise the class,

    enemy1 = Enemy()
    enemy1.attack()
    enemy1.checkLife()