18/7 Review


#1

can somone please tell me what is wrong with this code thanks. maybe its cuz its late but. i think this should do it.

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

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

#2

Traceback (most recent call last):
  File "python", line 17, in <module>
  File "python", line 8, in display_car
UnboundLocalError: local variable 'mpg' referenced before assignment

#3

To this

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

#4

@zeziba

I tried chaning the method display_car as you recommended.

this is what comes up in the interperter

<bound method Car.display_car of <Car object at 0x7f34ab3f47d0>>

then gives me the error

You should get a description of my_car by calling my_car.display_car().

so now my code looks like this

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

        

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

#5

This has to be this,

print my_car.display_car()

EDIT:

Delete this line

mpg = str(mpg)

#6

hmm, I'm confused on why that worked. can you explain this?


#7

You were creating a variable that was then referencing a variable called mpg which you never created in your code before that so it could not create a new variable with the information you provided.


#8

oh, So it doesn't carry over from previous methods in the class?


#9

When you declare a self.variable in the init part of the class in order to use it from then on out you have to use self.variable. The same for any class method you created.