__repr__ and __str__

class Car:
def init(self, model, mileage):
self.model = model
self.mileage = mileage
def str(self):
return “{}, {}”.format(self.model, self.mileage)
def repr(self):
return “{}”.format(self.model)
def eq(self, other):
return self.mileage == other.mileage
def add(self, other):
return self.mileage + other.mileage

c1 = Car(“City”, 17)
c2 = Car(“Civic”, 14)

Now if I do print(c1)

the output is not as expected…

the output should have been ‘City’

but its actually showing:-
City, 17
why the mileage is also getting printed? I didn’t modify my repr under in that way: I modified that only to return self. model so it should have shown only ‘City’.
What’s wrong with it?

hey @bihan ,
str function returns the string value of class , be it be a class name or something else , as changed.

but repr function always returns a class object representation.

try using your code in the following manner

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.