Specific type for attributes

Asked

Viewed 29 times

0

I’m trying to define the type of information that attributes receive, but I’m not sure how to do it. I tried these methods, but they do nothing.

    class Lancamento:
        def __init__(self, tipo, data, descricao, valor, conta,
                     categoria, tag, repeticao, pago):
            self.tipo = tipo
            self.data = data
            self.descricao = descricao
            self._valor = valor
            self.conta = conta
            self.categoria = categoria
            self.tag = tag
            self.repeticao = repeticao
            self.pago = pago

        @property
        def valor(self):
            return self._valor

        @valor.setter
        def valor(self):
            if type(self._valor) != float:
                raise ValueError("...")
#    @valor.setter
#    def valor(self, value):
#        if not isinstance(value, float):
#            print("Precisa ser float")

The part in comment was another method, which also did not return the desired, because the object can still be built with any type.

  • Why in __init__ you did self._valor = valor instead of self.valor = valor? The second way you will be using the property you defined.

  • @Woss If I put self.value = value I have a return of self.value = value Typeerror: value() takes 1 positional argument but 2 Were Given

  • True, in your setter a parameter was missing. O setter of a property always takes two parameters: the self and the new value of the property that has been assigned, as it did in the commented code.

  • I was able to solve the problem by constructing the class <code> if value < 0: raise Valueerror("Can’t be negative") Elif not isinstance(value, float): raise Valueerror("Needs to be float") Else: self. _value = value </code> @Woss

  • It wasn’t simpler to fix the property?

  • I started programming in python recently, and the material I found to solve this problem did not generate the expected result, only this solution. Not even the direction proposed to me here (and which I marked as the answer) was effective in solving the problem.

Show 1 more comment
No answers

Browser other questions tagged

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