7. Creating clas methods


Few wrap up questions on classes:

Why can't I write % in front of each variable as in the code below?
Why do I not need model/color/mpg in display_car method?
how does my_car.display_car() recognise the model/color/mpg

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.condition
print my_car.display_car()


Because outside of a string, we can only use % to tell Python to expect a parameter list. A single variable can be written as is, but multiple variables need to be in a tuple.

" ... " % (self.color, self.model, str(self.mpg))


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