Python 获取 __str__ 方法错误

0 投票
1 回答
615 浏览
提问于 2025-04-18 12:51

我正在通过一本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'对象不可调用”:

>>> 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__()这个函数呢?谢谢。

1 个回答

3

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

    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)

或者使用获取方法。

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

撰写回答