python 3 : TypeError: 'int' object is not callable

标签 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)

这里我调用了.area(),我想问题出在哪里:

    r1.area(3,4)
    print (r1)

最佳答案

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

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

希望这对您有所帮助!

关于 python 3 : TypeError: 'int' object is not callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37090650/

相关文章:

python - 相对导入的问题

python - 类型错误 : not enough arguments for format string in python

c++ - 错误 LNK2019 : unresolved external symbol "..." referenced in function _main

Python - Dash 从 Excel 文件创建堆积条形图

python - 使用 Pandas 数据框中的值作为另一个数据框中的列名

python - 传递切碎的日期时间

python - 着色 Voronoi 图

oop - 为什么 oop 语言没有 'read only' 访问修饰符?

PHP - 实现日志记录机制以在多个类中归档

python - 按日期和列名称匹配 2 个数据框以获取值