Creating class methods


#1

Traceback (most recent call last):
File "python", line 15, in
File "python", line 8, in display_car
TypeError: 'str' object is not callable

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 %, %, with, % MPG" (str(self.color),str(self.model),str(self.mpg))

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

#2

Hi @codesurfer82527,

In this line, you have only % in the format string, wherever you should have %s format specifiers ...

    print "This is a %, %, with, % MPG" (str(self.color),str(self.model),str(self.mpg))

You are also missing a % operator between the format string and the tuple of output expressions.

Note, also, that the required output includes a period at the end of the sentence.


#3

I did the change

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

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

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

error:
File "python", line 9
print This is a %, %, with, % MPG. % (str(self.color),str(self.model),str(self.mpg))
^
SyntaxError: invalid syntax

Oops, try again. Did you accidentally delete my_car?


#4

you are still using the wrong formatting (%). replace the first three % with %s and remove the commas. Moreover, color and model are already string, so you dont necessarily need convert them to str again. so your line 9 will be like this:
print "This is a %s %s with %s MPG." % (self.color,self.model, str(self.mpg))
hope this helps


#5

What is %. what is the difference between % and %s ?


#6

%s is for string formatting. % a call to turple.


#7

so our code should be
print "This is a %s %s with %s "MPG."" % (self.color,self.model,str(self.mpg))
Please correct me if wrong.


#8

Thanks a lot it ran now.
great !!

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 %s %s with %s MPG." % (self.color,self.model,str(self.mpg))

my_car = Car("DeLorean", "silver", 88)
print my_car.display_car()

print my_car.condition

print my_car.model

print my_car.color

print my_car.mpg


#9