Problems starting methods in a python class?

1

I'm new to python and I started with classes now, I 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 do not understand, use self.life = life no longer initializes life? And another if I want life to start as a set value how should I do?

self.vida = vida = 10

or

def __init__(self, vida = 10):
    self.vida = vida 
    
asked by anonymous 10.08.2018 / 22:57

1 answer

3

You have the class:

class Inimigo:

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


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


inimigo1 = Inimigo()

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

In this case, what you need to do is:

inimigo = Inimigo(10)

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

Notice that Python allows you to define named parameters, which in some cases makes the code much more readable. For example:

inimigo = Inimigo(vida=10)

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

If you do not want to always set a value, you can set a default value for the parameter, just like 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, to use changeable types as default values in the parameters.

Readings

10.08.2018 / 23:23