Get and Set using PROPERTY - Python3

1

As a property learning object, I created a small currency converter. See:

class converteMoeda():


  def __init__(self, dollar=0, real=0):
    self.dollar = dollar
    self.real = real

  def toDollar(self):
    dollar = self.real/self.dollar
    print("Convertendo Reais para Dólar.")
    return(dollar)

  def toReais(self):
    reais = self.dollar/self.reais
    print("Convertendo de Dólar para Reais.")
    return(reais)

  def setDollar(self,dollar):
    print("Gravando valor do dólar.")
    self._dollar = dollar
  def setReais(self,real):
    print("Gravando valor do real.")
    self._real = real

  def getDollar(self):
    print("Recuperando valor do dólar.")
    return(_dollar)
  def getReais(self):
    print("Recuperando valor do Real.")
    reutrn(_real)

  real = property(getReais,toReais)
  dollar = property(getDollar,toDollar)

c = converteMoeda()
c.toReais(3.17)

However, for a reason that I could not identify, it is generating a parameter number error:

Traceback (most recent call last):
  File "python", line 35, in <module>
  File "python", line 5, in __init__
TypeError: toDollar() takes 1 positional argument but 2 were given

Can anyone help me with this adventure?

    
asked by anonymous 28.06.2017 / 16:44

1 answer

2

I created a small example that defaults to the value of dollar in 3.3, you can change and access this value in an instance of the class through the property and setter us .

( TL; DR )

class Convert:

    def __init__(self):
        self.us = 3.3

    def to_dollar(self, real=0):
        return real/self.__us

    @property
    def us(self):
        return self.__us

    @us.setter
    def us(self, us):
        self.__us = us

c = Convert()
reais = 16.67

Using @property us:

print ('valor atual do dollar: ', c.us)
valor atual do dollar:  3.3

Using the to_dollar method for conversion:

print('Conversão de',reais,'reais em dollar: ',c.to_dollar(reais))
Conversão de 16.67 reais em dollar:  5.051515151515153

Using us.setter :

c.us = 3.10
print ('Valor Atualizado do dollar: ',c.us)
Valor Atualizado do dollar:  3.1

New conversion after updating with setter:

print('Conversão de',reais,'reais em dollar: ',c.to_dollar(reais))
Conversão de 16.67 reais em dollar:  5.37741935483871

View the code running on repl.it.

    
28.06.2017 / 18:35