Python3:TypeError:'int'对象不可调用

She*_*ing 2 python oop python-3.x

Python3:TypeError: 'int' object is not callable是因为我调用方法的.area()方式错了吗?或者是因为我说的方式.area()是错的?谢谢

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)
Run Code Online (Sandbox Code Playgroud)

在这里我打电话.area(),我想问题来自哪里:

    r1.area(3,4)
    print (r1)
Run Code Online (Sandbox Code Playgroud)

lin*_*usg 6

这是因为你首先定义了一个变量area(一个特定的整数)作为你的类的属性Rectangle,后来又定义了一个函数area().

这种不一致会导致混淆,因此Python解释器会尝试将整数调用为失败的函数.只需重命名整数变量(self.area = ...)或函数(def area(...))之一,一切都应该正常工作.

希望这可以帮助!