Python串联串联

时间:2013-08-20 19:07:15

标签: 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()

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

5 个答案:

答案 0 :(得分:5)

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

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

或者,您可以使用format

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

两个版本都打印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)

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

答案 1 :(得分:4)

改变这个:

def display_car(self):
    return "This is a "+ self.color + self.model+ " with "+str(self.mpg)+"MPG"

您看,display_car方法必须返回要打印的值。或者,您可以保留display_car(),但请调用此方法:

my_car = Car("DeLorean", "silver", 88)
my_car.display_car()

答案 2 :(得分:1)

print中的print my_car.display_car()是多余的,因为您已经在display_car方法中打印了该语句。因此,您获得额外的None

答案 3 :(得分:1)

如果你没有返回任何内容,Python会隐式返回None,因此print调用print的函数也会print None

答案 4 :(得分:0)

该行

print my_car.display_car()

应该是

my_car.display_car()