Python串联串联

2 python class concatenation

我正在做python编程,这是它的类单元.并且代码没有打印出正确的答案.

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
    def display_car(self):
        print "This is a "+ self.color + self.model+ " with "+str(self.mpg)+"MPG"

my_car = Car("DeLorean", "silver", 88)
print my_car.display_car()
Run Code Online (Sandbox Code Playgroud)

我正在尝试打印 这是一款带有88 MPG的银色DeLorean.

ale*_*cxe 5

请尝试使用此版本的display_car方法:

def display_car(self):
    print "This is a %s %s with %d MPG." % (self.color, self.model, self.mpg)
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用format:

def display_car(self):
    print "This is a {0} {1} with {2} MPG.".format(self.color, self.model, self.mpg)
Run Code Online (Sandbox Code Playgroud)

两个版本打印 This is a silver DeLorean with 88 MPG.

我认为你看到两个版本都比你的字符串连接更具可读性.

您可以使用format命名参数使其更具可读性:

def display_car(self):
    print "This is a {color} {model} with {mpg} MPG.".format(color=self.color, model=self.model, mpg=self.mpg)
Run Code Online (Sandbox Code Playgroud)

此外,您也None打印过 - 替换print my_car.display_car()my_car.display_car().