7. Creating Class Methods


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



print my_car.display_car

calling a method requires parentheses (just like calling functions)


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?


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


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


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


you're most welcome :slight_smile:


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