How can I return a string of my car’s instance variables?

Question

How can I return a string of my car’s instance variables?

Answer

Recall that to print a string containing variables, it’s easy to use string formatting using the %s placeholder, followed by a % (list, of, variables) after the string. Here’s an example:

# If we have instance variables:
# self.str_string = "string"
# self.var_string = "variables"
# self.formatting_string = "string formatting"
# Then we can return a string using all three like this:
return "This is a %s with a couple %s inserted with %s!" % (self.str_string, self.var_string, self.formatting_string)
5 Likes
def display_car(self):
    return "This is a %s %s with %s MPG." % (self.color, self.model, self.mpg)

Why do we need to use dot notation which attaches the ‘self’ argument to each of the other arguments when this has already been done in the function above it (below this question)?

 def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg

My guess:

Summary

Because of the scope. Creating a variable called model on the global scope would trigger the “variable found let’s compute this”, because it looks for the variable in the global scope first. In case the global scope variable (same name) has nothing to do with what you’re trying to do, you want it to use the variable from it’s own scope. The self. tells it to look in it’s own scope first.

Hope I’m not too far off with that.

6 Likes

No, that makes sense to me.

Thanks!

1 Like

Instructions say:

You can use the str() function to turn your mpg into a string when creating the display string.

My code for this exercise:

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

I used %s for mpg integer and it worked. Before that I also tried %d and it worked. Where exactly should I use the instruction above (the str())?

1 Like

I used str() around the “self.mpg” and it also worked that way, but since it seems to work without doing that, I’m guessing it’s fine your way too.