Creating class methods


#1



https://www.codecademy.com/courses/python-intermediate-en-egNXj/1/1?curriculum_id=4f89dab3d788890003000096#


My code does not throw any errors on the interpreter. Moreover, it prints exactly what was asked in the question.

Yet I get this at the bottom: Oops, try again. It looks like you didn't print "This is a silver DeLorean with 88 MPG.".


Why is that?


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


#2

this line:

print "This is a", self.color, self.model, "with", str(self.mpg) , "MPG."

Should be returned, not printed.

Also, as I side note, I would go ahead and remove that whitespace after str(self.mpg)... It may be messing with the overall string some.


#3

Thanks! Should've read the question properly. Sorry for wasting your time.


#4

Actually, upon further investigation, for some reason the SCT for this exercise doesn't seem to like us using comma (,) notation. As far as I can gather, It will only accept one of the following:

Plus (+) Notation:

print "This is a " + self.color + " " + self.model + " with " + str(self.mpg) + " MPG."

or

%s Notation:

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

#5

The plus notation works as expected. But to get the comma working, I had to use this convoluted solution because the function returns a list of strings.

So:

return "This is a", self.color, self.model, "with", str(self.mpg) , "MPG."

followed by

print " ".join(my_car.display_car())

#6

Yes, using " ".join() works too...


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.