20. Classes. 7. Creating class methods


#1



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


The code prints out correctly (i.e. the console shows what I want with no error thrown. Codecademy throws this error though:
Oops, try again. Make sure you pass the self keyword to the display_car() method.


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

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


#2

self is another object, by creating variables belonging to this object (self.model, self.color, self.mpg) in __init__(), we can access this variables through self in display_car method, which means display_car method only need a single parameter, which is self


#3

Cool thanks. Just for others' reference the correct code is:

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

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

#4

nicely done :slight_smile: I had too help a lot of people of late who would struggle with such instructions, nice that you where able to figure it out by taking a moment to think about it, and think about what everything means, which is a good skill for a programmer :slight_smile: More people like you would be great


#5

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