Python得到__str__方法错误

时间:2014-07-10 19:32:27

标签: python oop constructor

我正在从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 个答案:

答案 0 :(得分:3)

您正在尝试调用字符串。

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

你需要离开&#34;()&#34;出:

    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())