7. Creating class methods


#1



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

Hello, I keep getting the following message:

Traceback (most recent call last):
File "python", line 15, in
AttributeError: 'Car' object has no attribute 'display_car'

Could someone please explain what is wrong with this code?
Thank you.


class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

my_car = Car("DeLorean", "silver", 88)
print my_car.condition
print my_car.model
print my_car.color
print my_car.mpg

def display_car (self):
    print ( "This is a %s %s with %s MPG."%(self.color, self.model, self.mpg))
    
my_car = Car("DeLorean", "silver", 88)

print my_car.display_car()


#2

@hjb240:

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


That's because your function should be inside your Car class, not outside of it :slight_smile:

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."

#3

Thank you g4be, for your help. I moved the function to appear inside the Car class, but I get the message:

Oops, try again. It looks like you didn't print "This is a silver DeLorean with 88 MPG.".

The odd thing is that the output DID print "This is a silver DeLorean with 88 MPG", but it is followed by:

None
None

Could you please help me understand what is happening here? Thank you!

This is what I have now:

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


#4

@hjb240:
Your output:

"This is a silver DeLorean with 88 MPG"

Expected output:

"This is a silver DeLorean with 88 MPG."

You forgot the dot at the end of your phrase :sunny:


#5

This is my code. It works!

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, self.mpg))
    
my_car = Car("DeLorean", "silver", 88)

print my_car.display_car()

How does mpg turn to str?
#6

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