【发布时间】: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