Python - 为什么 __str__ 在调用时想要返回一些东西?我在 __str__ 中有打印函数

标签 python class python-2.7 return

我正在用 Python 构建一个简单的类。我已经定义了我自己的 __str__ 方法,当我在类的一个实例上调用 print 时,它应该能很好地工作。当我创建该类的实例并对其调用 print 时,出现错误:

TypeError: __str__ returned non-string (type NoneType)

我理解这个错误,它告诉我函数没有返回任何东西(它返回了None)

class Car(object):

    def __init__(self, typ, make, model, color, year, miles):
        self.typ = typ
        self.make = make
        self.model = model
        self.color = color.lower()
        self.year = year
        self.miles = miles

    def __str__(self):
        print('Vehicle Type: ' + str(self.typ))
        print('Make: ' + str(self.make))
        print('Model: ' + str(self.model))
        print('Year: ' + str(self.year))
        print('Miles: ' + str(self.miles))
        #return ''  # I can avoid getting an error if I un-comment this line

bmw = Car('SUV', 'BMW', 'X5', 'silver', 2003, 12030)
print bmw

如您所见,我的 __str__ 函数包含我想要的所有打印语句。我不需要它返回任何东西。这是我想要的输出。

Vehicle Type: SUV
Make: BMW
Model: X5
Year: 2003
Miles: 12030

我怎样才能得到这个输出? 我已尝试这样做以避免打印错误,但错误仍然出现:

def __str__(self):
    try:
        print('Vehicle Type: ' + str(self.typ))
        print('Make: ' + str(self.make))
        print('Model: ' + str(self.model))
        print('Year: ' + str(self.year))
        print('Miles: ' + str(self.miles))
    except:
        pass

最佳答案

根据 __str__文档,

Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from repr() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

因此,__str__ 返回的值必须是一个字符串,在您的情况下,您没有返回任何内容,因此 Python 默认返回 None

您可以通过简单地更改 __str__ 函数来获得所需的输出,如下所示

def __str__(self):
    return "Vehicle Type: {}\nMake: {}\nModel: {}\nYear: {}\nMiles: {}" \
        .format(self.typ, self.make, self.model, self.year, self.miles)

关于Python - 为什么 __str__ 在调用时想要返回一些东西?我在 __str__ 中有打印函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21364806/

相关文章:

python - 我是否正确地为曲线拟合模型编写了代码?除了线性回归之外,每个模型的这条线都偏离得很远

python - 如何使用 django 信号访问字段

Python:导入模块

c++ - 如何在C++中重新声明类对象?

Python:对象没有属性错误:一个数组

sql - Python 中的动态 INSERT 语句

python - 无法使用的函数参数

python - 如何找到每个客户的相似地址数量?

javascript - es6 类可以具有公共(public)属性和功能吗?

python - 读取文本文件的每一行并确定它是否还有另一个字母