Set instance attribute automatically from parameters of another instance attribute (same class)

Asked

Viewed 53 times

-1

Good afternoon or good night. I was doing the POO course of Gustavo Guanabara which is in PHP, in class 7b is defined a rule where from the instance weight attribute is defined the category attribute. I couldn’t do this automatically in python, just manually changing the weight and setting the rules in the weight Setter. As the following code shows. Does anyone have any idea how I can emulate this behavior?

class Lutador(object):
    # Atributos
    def __init__(self, pe, ca):
        self._peso = float(pe)
        self._categoria = str(ca)

    #peso
    @property
    def peso(self):
        return self._peso

    @peso.setter
    def peso(self, pe):
        self._peso = pe
        if self._peso < 52.2:
            self._categoria = 'invalido'

    #categoria
    @property
    def categoria(self):
        return self._categoria

    @categoria.setter
    def categoria(self, ca):
        self._categoria = ca

Execution:

an = Lutador(55.2, 'a')
an.peso = 51.1
print(an.peso)
print(an.categoria)
  • do an if inside the __init__ wouldn’t work for this case? Like if peso >= valor: self.__categoria = (nome da categoria ou codigo)

  • put the rules - a sequence of if/Elif/etc. in the category getter. If the category depends only on the value of the weight, you do not need a category Setter, nor the internal attribute ._categoria.

  • Complementing the previous comment, if the category depends solely on the value of the weight, it also does not make sense to pass it on the builder, who should receive only the weight...

  • Our staff thank you so much for answering the question, it worked even, I’m still studying POO and had not understood right the syntax of getters and setters in python. Thank you very much again

1 answer

0

I hope I’ve helped

class Lutador(object):
    # Atributos
    def __init__(self, pe):
        self._peso = float(pe)

    def classificar(self):
        if self._peso < 52.2:
            self._categoria = 'invalido'
        else:
            self._categoria = 'valido'

    #peso
    @property
    def peso(self):
        return self._peso

    @peso.setter
    def peso(self, pe):
        self._peso = pe
        self.classificar()

    #categoria
    @property
    def categoria(self):
        try:
            return self._categoria
        except:
            self.classificar()
            return self._categoria

    @categoria.setter
    def categoria(self, ca):
        self._categoria = ca

Browser other questions tagged

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