2

I'm doing python programming and this is class unit of that. and the code is not printing the right answer.

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()

I'm trying to print This is a silver DeLorean with 88 MPG.

4

5 回答 5

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().

于 2013-08-20T19:08:25.977 回答
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()
于 2013-08-20T19:10:04.573 回答
1

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

于 2013-08-20T19:08:46.523 回答
1

None如果您不返回任何内容,Python 会隐式返回,因此print调用的函数也printprint None.

于 2013-08-20T19:10:43.827 回答
0

线

print my_car.display_car()

应该

my_car.display_car()
于 2013-08-20T19:22:48.890 回答