What does __str__ method do?
python - How to use __str__ function to return a string representation of a class - Stack Overflow
__str__() question
python - What is the purpose of __str__ and __repr__? - Stack Overflow
I'm still a beginner in python and my English is not really good, so I may have a little bit of understanding the explanation given in my course.
So I have this code:
class Apple:
def __init__ (self,color,flavor):
self.color=color
self.flavor=flavor
def __str__(self):
return "This apple is {} and its flavor is {}".format(self.name,self.flavor)
jonagold=Apple("red","sweet")
print(jonagold)The only purpose I see in using the __str__ method, I don't have to write the method in the print () line. If I changed the __str__ method with:
def say(self):
return "This apple is {} and its flavor is {}".format(self.name,self.flavor)I would just need to type
print(jonagold.say())
And I would get the same answer. What are the other purpose of using __str__? In what situation would I need to use the __str__?
Thank you :)
I've been teaching myself Python using the Python Crash Course book, and now that I've reached the end of it I've been going through various tutorial websites to practice/supplement what I've learned. However, I've run into something strange.
As far as I can see, the Python Crash Course book does not mention __str__(). When I started looking at some class tutorials, as that's something I'm struggling with, I've run into examples where they use a method called __str__().
I'm shaky as to what it does, and I'm even more confused by the examples. I see one on https://www.w3schools.com/python/python_classes.asp which uses the following code:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)When run, it returns John 36. Then there's another example where the __str__() method is not used, and it returns <__main__.Person object at 0x15039e602100>.
Okay, fine. So I need to use __str__() for this to work. But in the Python Crash Course, it shows an example with a similar class, and it does not use a __str__() method, and it works fine:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self. year = year
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
my_new_car = Car("Audi", "a4", "2024")
print(my_new_car.get_descriptive_name())This returns "2004 Audi A4". But it does not use a __str__() method. Why?
__repr__
Called by the
repr()built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).
__str__
Called by the
str()built-in function and by the print statement to compute the "informal" string representation of an object.
Use __str__ if you have a class, and you'll want an informative/informal output, whenever you use this object as part of string. E.g. you can define __str__ methods for Django models, which then gets rendered in the Django administration interface. Instead of something like <Model object> you'll get like first and last name of a person, the name and date of an event, etc.
__repr__ and __str__ are similar, in fact sometimes equal (Example from BaseSet class in sets.py from the standard library):
def __repr__(self):
"""Return string representation of a set.
This looks like 'Set([<list of elements>])'.
"""
return self._repr()
# __str__ is the same as __repr__
__str__ = __repr__
The one place where you use them both a lot is in an interactive session. If you print an object then its __str__ method will get called, whereas if you just use an object by itself then its __repr__ is shown:
>>> from decimal import Decimal
>>> a = Decimal(1.25)
>>> print(a)
1.25 <---- this is from __str__
>>> a
Decimal('1.25') <---- this is from __repr__
The __str__ is intended to be as human-readable as possible, whereas the __repr__ should aim to be something that could be used to recreate the object, although it often won't be exactly how it was created, as in this case.
It's also not unusual for both __str__ and __repr__ to return the same value (certainly for built-in types).