7. Creating Class Methods


#1



7. Creating class methods


<bound method Car.display_car of >


Hoping it would work . . .


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 {} {} with {} MPG.".format(color,model,mpg)
my_car = Car("DeLorean", "silver", 88)
print my_car.display_car


#2

here:

print my_car.display_car

calling a method requires parentheses (just like calling functions)


#3

Cool thanks but now it is giving this error.

Traceback (most recent call last):
File "python", line 10, in
File "python", line 8, in display_car
NameError: global name 'color' is not defined

Is the .format messing this up?


#4

What I mean is, does .format only reference variables outside of the class?


#5

no, .format() is fine. The problem is that color, model and mpg are undefined variable, where do you think you defined them?

there is a reason we create instance variable (self.model and so on) in init, so we can access instance variable in other methods through self


#6

Ah ha! Just talked through that one. Thanks for not just giving me the answer


#7

you're most welcome :slight_smile:


#8

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