【问题标题】:'Float' and 'str' objects are not callable'Float' 和 'str' 对象不可调用
【发布时间】:2021-11-20 20:28:51
【问题描述】:

我有一个名为 Circle 的类,它构造一个具有给定名称和半径的圆。我得到了一组要传递的断言,我得到一个 TypeError:'str' object is not callable 和 TypeError:'float' object is not callable for methods name() and radius()。

import math


class Circle:

def __init__(self, name: str, radius: float = 5):
    pass  # TODO
    self.radius = radius
    self.name = name

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

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

def name(self):
    """
    Returns the name of this Circle.
    """
    pass  # TODO
    return str(self.name)
if __name__ == '__main__':
    test1 = Circle('Mike', 10)
    assert test1.name() == 'Mike'
    assert test1.radius() == 10
    assert test1.size() == 314.159

【问题讨论】:

  • 所以不要用数字覆盖方法?
  • 同时拥有一个数据成员 name 和一个名为 name() 的方法,它可以隐藏它以返回其字符串表示形式,这似乎既矫枉过正,又完全不是 Pythonic。这不是 Java。我们只引用str(self.name)(或在隐式转换为字符串的上下文中使用self.name,例如print)。

标签: python


【解决方案1】:

您可以像这样在实例变量之前简单地添加 _

import math


class Circle:

    def __init__(self, name: str, radius: float = 5):
        pass  # TODO
        self._radius = radius
        self._name = name

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

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

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

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

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 2011-06-07
    • 2019-03-05
    相关资源
    最近更新 更多