【问题标题】:Python getting a __str__ method errorPython 得到一个 __str__ 方法错误
【发布时间】:2014-09-01 07:35:59
【问题描述】:

我正在从一本 Python 编程书中学习 OOP,其中一个示例是关于使用 __str__() 函数通过 print() 语句显示属性值。这本书不清楚,我想我在这里遗漏了一些重要的东西:

  class Product:
    def __init__(self, description, price, inventory):
        self.__description = description
        self.__price = price
        self.__inventory = inventory

    def __str__(self):
        return '{0} - price: {1:.2f}, inventory: {2:d}'.format(self.__description(), self.__price(), self.__inventory())

    def get_description(self):
        return self.__description

    def get_price(self):
        return self.__price

    def get_inventory(self):
        return self.__inventory

当我运行模块、创建一个对象并使用print() 函数时,我收到以下错误,它说“'str' object is not callable”:

>>> prod1 = Product('tomato', 1.50, 20)
>>> print(prod1)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print(prod1)
  File "C:/Users/person/Documents/GitHub/pyprojects/inittest.py", line 8, in __str__
    return '{0} - price: {1:.2f}, inventory: {2:d}'.format(self.__description(), self.__price(), self.__inventory())
TypeError: 'str' object is not callable
>>> 

我应该如何处理__str__() 函数?谢谢。

【问题讨论】:

  • 您使用的是self.__description(),但您的真正意思是self.__description,或self.get_description()self.__price()self.__inventory() 也是如此。
  • 不要在标识符的开头使用__。这将调用private name mangling,它通常会执行您不想要的操作,并且不能替代 Java/C++ 中的private 范围
  • 不要写琐碎的“getter”。它们是来自 C++/Java 的反模式。最好使用my_product.inventory 而不是my_product.get_inventory()。与其他语言不同,如果您需要稍后添加方法来维护成员不变量,您可以这样做而无需更改每个提到 *.inventory 的地方。

标签: python oop constructor


【解决方案1】:

你正在尝试调用一个字符串。

    def __str__(self):
        return '{0} - price: {1:.2f}, inventory: {2:d}'.format(self.__description(), self.__price(), self.__inventory())

您需要留下“()”:

    def __str__(self):
        return '{0} - price: {1:.2f}, inventory: {2:d}'.format(self.__description, self.__price, self.__inventory)

或者使用getter方法

    def __str__(self):
        return '{0} - price: {1:.2f}, inventory: {2:d}'.format(self.get__description(), self.get__price(), self.get__inventory())

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2018-01-02
    • 2017-08-25
    • 2014-11-17
    • 1970-01-01
    相关资源
    最近更新 更多