【发布时间】:2014-02-17 08:15:18
【问题描述】:
我正在用 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__用于str用于获取文本表示。你不总是想打印这个表示,你希望它返回这个表示,以便人们可以用它做其他事情:将它嵌入到其他文本中,将其写入一个文件(不重定向标准输出),对其进行字符串操作,将其存储在数据结构中以备后用等。它应该被打印出来,就像print(vehicle)一样简单,因为@987654332 @呼叫str。返回文本表示比打印它更通用。
标签: python class python-2.7 return