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

1

5

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
Rochelrochell answered 13/6, 2017 at 4:52 Comment(4)
enemy1 = Enemy is not how instantiate and Enemy object. You've just assigned the Enemy class to the variable enemy1.Pugilist
Enemy is the class. Enemy() is a new instance of the class. Set enemy1 to the latter.Fugacious
pythontips.com/2013/08/07/the-self-variable-in-python-explainedAndrel
Thank you guys, that workedRochelrochell
E
7

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

enemy1 = Enemy()
enemy1.attack()
enemy1.checkLife()
Evenings answered 13/6, 2017 at 4:53 Comment(4)
Would you please do me a favour and tag the answer as selected, then?Evenings
Sure. It says I have to wait 7 minutes before doing so. So I'll flag it as accepted in 7 minutes.Rochelrochell
Appreciate the support brother!!Evenings
No problem :) I went ahead and selected your answerRochelrochell

© 2022 - 2024 — McMap. All rights reserved.