Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python error: missing 1 required positional argument: 'self' [duplicate]

Tags:

python

class

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
like image 229
Liam Hayes Avatar asked Jun 13 '17 04:06

Liam Hayes


1 Answers

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

enemy1 = Enemy()
enemy1.attack()
enemy1.checkLife()
like image 140
zaidfazil Avatar answered Oct 27 '22 00:10

zaidfazil