Problems starting methods in a python class?

Asked

Viewed 98 times

1

I’m new to python and started with classes now, tried to start a class
but for some reason always gives error, the error changes but always gives, at the moment I am with the code this way :

class Inimigo:

    def __init__(self, vida):
        self.vida = vida 


    def ataque(self):
        self.vida -= 2


    inimigo1 = Inimigo()

However the error that returns is :

__init__() missing 1 required positional argument: 'vida'

I don’t understand, using the self.life = life no longer initializes life? And another if I want life to begin as a value defined as I must do?

self.vida = vida = 10

or

def __init__(self, vida = 10):
    self.vida = vida 

1 answer

3


You have the class:

class Inimigo:

    def __init__(self, vida):
        self.vida = vida 


    def ataque(self):
        self.vida -= 2


inimigo1 = Inimigo()

In the class initializer, you have a parameter vida, which will be the value of self.vida. However, when instantiating the class, you pass no value. If you do not define, what should be the value of vida?

In this case, what you’ll need to do is:

inimigo = Inimigo(10)

Thus, vida will receive the value 10 and therefore, self.vida will be 10.

Note that Python allows you to define named parameters, which at times makes code much more readable. For example:

inimigo = Inimigo(vida=10)

Making it clear that 10 is life, not the power of attack, for example.

If you don’t want to always set a value, you can set a default value for the parameter, just as you did at the end of your question:

def __init__(self, vida=10):
    self.vida = vida

So even if you do:

inimigo = Inimigo()

The value of self.vida will be 10.

One caution you should take is the default value of the parameter will be evaluated in the class definition, so avoid, unless it makes sense, using mutable types as default values in the parameters.

Readings

Browser other questions tagged

You are not signed in. Login or sign up in order to post.