You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python自定义Circle类调用name()、radius()方法触发str/float对象不可调用报错

错误原因
  • 命名冲突:构造方法中绑定的实例属性self.name、self.radius和类中定义的name()、radius()方法完全同名,Python中实例属性的访问优先级高于类方法,调用时会优先拿到属性值而非方法,加括号调用非可调用类型就会触发对应报错。
  • 原代码存在缩进错误:Circle类下的所有方法都没有正确缩进,不符合Python语法规范。
修正代码
import math


class Circle:
    def __init__(self, name: str, radius: float = 5):
        self._radius = radius
        self._name = name

    def radius(self) -> float:
        """
        Returns the radius of this Circle.
        """
        return float(self._radius)

    def size(self) -> float:
        """
        Returns the size of this Circle, i.e. the area of the circle.
        """
        size_area = math.pi * pow(self._radius, 2)
        return round(size_area, 3)

    def name(self):
        """
        Returns the name of this Circle.
        """
        return str(self._name)


if __name__ == '__main__':
    test1 = Circle('Mike', 10)
    assert test1.name() == 'Mike'
    assert test1.radius() == 10
    assert test1.size() == 314.159

修正后运行代码可直接通过所有断言测试。

内容的提问来源于stack exchange,提问作者user11505855

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:54:03