Creating class methods - Why str(self.mpg))?


Why in this instance do we use str(self.mpg)) - this is the first time I have seen this used when calling the attribute of a Class.

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


That’s entirely redundant.

%s already does exactly that.


That’s what I thought, but that was the code given by Code academy.


Also, there’s way nicer string interpolation since 3.6

print(f'This is a {self.color} {self.model} with {self.mpg} MPG.')

(prefixing the string with f and putting code in braces)

Pretty sure % for string formatting is discouraged now, don’t have any source to back that up right now though


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