Python - 为什么__str__需要在调用时返回的内容?我在__str__里面有打印功能

Vad*_*der 1 python return class python-2.7

我在python中构建一个简单的类.我已经定义了自己的__str__方法,当我在类的实例上调用print时,该方法应该可以很好地工作.当我创建一个类的实例并调用print它时,我收到一个错误:

TypeError: __str__ returned non-string (type NoneType)
Run Code Online (Sandbox Code Playgroud)

我理解这个错误,它告诉我函数没有返回任何东西(它返回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
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我的__str__函数包含了我想要的所有打印语句.我没有必要退货.这是我想要的输出.

Vehicle Type: SUV
Make: BMW
Model: X5
Year: 2003
Miles: 12030
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

the*_*eye 6

按照__str__文档,

由str()内置函数和print语句调用,以计算对象的"非正式"字符串表示形式.这与repr()的不同之处在于它不必是有效的Python表达式:可以使用更方便或简洁的表示.返回值必须是字符串对象.

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

您可以通过简单地更改__str__功能来获得所需的输出,就像这样

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