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


#1

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)

FAQ: Learn Python - Classes - Creating class methods