Object assignment in Python

Asked

Viewed 292 times

2

Can anyone tell me why in the first iteration the assignment retangulo=retangulo() works, but on Monday?

This error appears in Pycharm:

<<'rectangle' Object 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: ")
  • It worked, bro :) Thank you so much

1 answer

1

Can anyone tell me why in the first iteration the assignment retangulo = retangulo() works, but on Monday?

Because in the first iteration the class name is overwritten with an instance of the class itself, in the second iteration a instance 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 variable name 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 wear it like this:

retangulo = Retangulo()
ponto = Ponto()

retangulo.centro(ponto)

print(ponto.x, ponto.y)

See DEMO

Browser other questions tagged

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