Attribution of objects in Python

2

Can anyone tell me why in the first iteration the assignment retangulo=retangulo() works fine, but in the second it does not?

This error appears in Pycharm:

  

is not callable

Code:

from MDvalidateDATA import validateDATA

class ponto:

    def __init__(self,x=0,y=0):

        self.x=x

        self.y=y

class retangulo:

    def __init__(self):
        self.base=validateDATA("Digite a o valor da base(entre 1 1000): ",1000,1,"float")

        self.altura = validateDATA("Digite a o valor da altura(entre 1 1000): ", 1000, 1, "float")

    def centro(self,ponto):

        ponto.x=self.base/2

        ponto.y=self.altura/2


x="1"

while x=="1":

    retangulo=retangulo()

    ponto=ponto()

    retangulo.centro(ponto)

    print(ponto.x,ponto.y)

    x=input("Digite 1 para continuar ou quaklquer outra tecla pra sair: ")
    
asked by anonymous 04.09.2016 / 18:39

1 answer

1
  

Can anyone tell me why in the first iteration the assignment    retangulo = retangulo() works fine, but the second does not?

Because in the first iteration the class name is overwritten with an instance of the class itself, in the second iteration at instance of the class is overwritten again with NoneType , see

class ponto:
    def __init__(self):
        print ("Instância inicializada!")

    def __call__(self):
        print ("Instância foi chamada como função!")


print (type(ponto())) # <class '__main__.ponto'>
ponto = ponto()       # sobrescreve o nome da classe com uma instância de ponto 
print (type(ponto))   # <class '__main__.ponto'>
print (type(ponto())) # <class 'NoneType'>

# <class '__main__.ponto'>
# <class '__main__.ponto'>
# Instância foi chamada como função!
# <class 'NoneType'>

To resolve this change the name of the variable to something else, for example p or pt :

pt = ponto()

print (type(pt))      # <class '__main__.ponto'>
print (type(ponto())) # <class '__main__.ponto'>

Another way is to change the class name if you prefer to follow the convention , the initial letter of the name must be uppercase:

class Ponto:
    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y

class Retangulo:
    def __init__(self):
        self.base = int(input("Digite a o valor da base(entre 1 1000): "))
        self.altura = int(input("Digite a o valor da altura(entre 1 1000): "))

    def centro(self,ponto):
        ponto.x = self.base / 2
        ponto.y = self.altura / 2

And use like this:

retangulo = Retangulo()
ponto = Ponto()

retangulo.centro(ponto)

print(ponto.x, ponto.y)

See DEMO

    
05.09.2016 / 06:45