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
相关产品推荐
相关产品推荐

