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


#1

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



#2

That’s entirely redundant.

%s already does exactly that.


#3

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


#4

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


#5

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