I need to know how to achieve inheritance in my python program

Asked

Viewed 26 times

-1

from random import randint


class PersonagemP:
    def __init__(self, nome):
        self.nome = nome
        self.posicao = str('DEF')
        self.pontosATK = int(randint(5, 20))
        self.pontosDEF = int(randint(5, 20))
        self.pontosRFL = int(randint(5, 20))
        self.pontosLife = int(50)
        self.barraEspecial = int(3)


class Invocador(PersonagemP):
    def __init__(self, nome):
        super().__init__(nome, pontosATK, pontosDEF, pontosRFL, pontosLife, barraEspecial)
        self.nome = nome
        self.pontos_ATK = pontosATK - 3
        self.pontos_DEF = pontosDEF - 3
        self.pontos_RFL = pontosRFL - 3
        self.pontos_Life = pontosLife + 5
        self.barra_Especial = barraEspecial + 3


Main1 = Invocador('Pedro')
print(Main1)
print(Main1.nome)
print(Main1.pontosATK)

In this case I’m making a class for a role-playing game, but I need to use another class to make another type of character, in this case the first is to make the base character and the second is the heiress is forming a new type of character, but I’m not getting.

  • 1

    Just a hint, randint returns an integer so no need to convert using int. The same goes for str("DEF"), int(50) and the others.

1 answer

1


As you can see, in your class Pai, you have only one attribute in the constructor, the attribute nome, then your call in class Filho should pass only this attribute.

class Invocador(PersonagemP):
    def __init__(self, nome):
        super().__init__(nome)
        ...

Now how you need to fetch the values that have been set in your class Pai (the generated random values), you only need to use the self to refer to them.

class Invocador(PersonagemP):
    def __init__(self, nome):
        super().__init__(nome)
        self.nome = nome
        self.pontos_ATK = self.pontosATK - 3
        self.pontos_DEF = self.pontosDEF - 3
        self.pontos_RFL = self.pontosRFL - 3
        self.pontos_Life = self.pontosLife + 5
        self.barra_Especial = self.barraEspecial + 3

And as a test we will obtain something similar to

Main1 = Invocador('Pedro')
print(Main1)
print(Main1.nome)
print(Main1.pontosATK)

>> <__main__.Invocador object at 0x000002A033D5AB20>
>> Pedro
>> 15
  • 2

    A hint would be to change the names of variables in the class PersonagemP, for something like generatedATK, so there won’t be any confusion when it comes to knowing what your Invocador, which in your case is pontos_ATK and not pontosATK.

Browser other questions tagged

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