2

Python3: TypeError: 'int' object is not callable, is it because the way I called the method .area() is wrong? Or is it because the way I def the .area() is wrong? Thank you

class Rectangle: 
    def __init__ (self):
        self.height = 0
        self.width = 0
        self.area = 0

    def setData(self, height, width):
        self.height = height
        self.width = width

    def area(self, height, width):
        self.area = height * width

    def __str__(self):
        return "height = %i, width = %i" % (self.height, self.width)
        return "area = %i" % self.area

if __name__ == "__main__":
    r1 = Rectangle()
    print (r1)
    r1.setData(3,4)
    print (r1)

Here I call .area(), I think what's where the problem comes from:

    r1.area(3,4)
    print (r1)
AKS
  • 18,983
  • 3
  • 43
  • 54
Shengjing
  • 63
  • 1
  • 9

3 Answers3

7

It's because you first defined a variable area (an integer to be specific) as an attribute of your class Rectangle, and later a function area().

This inconsistency causes confusion so the Python interpreter tries to call the interger as a function which fails. Just rename one of the integer variable (self.area = ...) or the function (def area(...)), and everything should work fine.

Hope this helps!

linusg
  • 6,289
  • 4
  • 28
  • 78
2

You have name collision between the area method and the area field. It looks like you dont need the area field at all. And the arguments of the area function are not used. And you have two __str__ functions too. I attempted to fix it:

class Rectangle: 
    def __init__ (self):
        self.height = 0
        self.width = 0

    def setData(self, height, width):
        self.height = height
        self.width = width

    def __str__(self):
        return "height = %i, width = %i" % (self.height, self.width)

    def area(self):
        return self.height * self.width

if __name__ == "__main__":
    r1 = Rectangle()
    print (r1)
    r1.setData(3,4)
    print (r1)
    print ("area = ", r1.area())
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
1
def area(self, height, width):
    self.area = self.height * self.width

You are defining a method area and inside the method you overwrite it with an int.

C14L
  • 12,153
  • 4
  • 39
  • 52