我正在用 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/