Here is an example:

def __str__(self):
    return f'({self.self.country},{self.self.code},{self.self.product}, {self.cost},{self.quantity })'

This way, when you assign values to a class, you can print its string representation

print(new_shoe)

More info here https://www.pythontutorial.net/python-oop/python-str/

Answer from ssanga on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › what does __str__ method do?
r/learnpython on Reddit: What does __str__ method do?
November 14, 2020 -

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

What is __str__() Dec 19, 2020
r/learnpython
5y ago
__str__() question Jan 22, 2025
r/learnpython
last yr.
A beginner's guide to __str__ and __repr__ Sep 25, 2020
r/learnpython
6y ago
List of objects where __str__ is defined Jul 6, 2021
r/learnpython
5y ago
More results from reddit.com
🌐
Codecademy
codecademy.com › docs › python › dunder methods › __str__()
Python | Dunder Methods | __str__() | Codecademy
April 24, 2025 - The __str__() method, on the other hand, defines how an object should be converted to a string when using functions like str() or print(). They serve entirely different purposes: __init__() for object creation and __str__() for string representation.
Discussions

python - Difference between __str__(self) and show(self) - Stack Overflow
Explore Stack Internal ... Save this question. Show activity on this post. Just encountered an example Fraction class and am not too sure what the difference between these two methods is. Once __str__ has been implemented doesn't show become redundent ? def __str__(self): return str(self.n... More on stackoverflow.com
🌐 stackoverflow.com
python - def __str__(self): return str(self.name) in model - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. Here is my models.py. def str(self):return str(self.name) still won't change Product object (1) to the product name. More on stackoverflow.com
🌐 stackoverflow.com
Customize def __str__(self): method when creating a class in Python - Stack Overflow
I am creating a MultipleChoice class in Python3, where the first parameter is supposed to be a question, the second parameter a list with alternatives (each entry a string, not numbered), and the t... More on stackoverflow.com
🌐 stackoverflow.com
python - What is doing __str__ function in Django? - Stack Overflow
def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised. More on stackoverflow.com
🌐 stackoverflow.com
🌐
PERSONAL BLOG
snowcodes.hashnode.dev › class-in-py-str-repr-self-etc
class in py, __str__, __repr__, self etc - PERSONAL BLOG
August 7, 2023 - These methods are defined within ... ... __str__(self): This method returns a string representation of the object when it is used with the str() function or when the object is printed using print()....
🌐
Real Python
realpython.com › videos › how-and-when-use-str
How and When to Use .__str__() (Video) – Real Python
In this lesson, you’ll see one Pythonic way to convert Python objects into strings by using .__str__(). You’ll learn what .__str__() means as well and also learn how to use it in a Python class: ... class Car: def __init__(self, color, mileage): self.color = color self.mileage = mileage def __str__(self): return 'a {self.color} car'.format(self=self)
Published: March 4, 2019
Top answer
1 of 3
8

The purpose of having a __str__ method is to create a string representation of the object. __str__ should return a string. If the implementation of __str__ instead printed the string representation and returned nothing, when the object was used in a string context a TypeError will be raised. Take for example:

def __str__(self):
        print '%f/%f'%(self.num,self.den)

If we went to display a fraction object like so:

f = Fraction(1,2)
print f

we get an exception:

Traceback (most recent call last):
  File "/Users/.../Desktop/...", line 13, in <module>
    print f
TypeError: __str__ returned non-string (type NoneType)
>>> 

This is because __str__ is used to get the string representation of the object, not print it (by convention that is, you could print as long as you return a string). That's what the print statment/function is used for in conjunction with a __str__ method.

On the other hand a method like show:

def show(self):
        print(self.num,"/",self.den) #or even print(self) (for the last part of answer)

Is essentially equivalent to print(f) in the above case (except it includes spaces next to the operands). show is used to output the string representation, while __str__ to get the representation.

However, additional logic may be added to show which isn't appropriate/necessary when constructing a string representation, and hence make sense to have both methods.

You can however use a method like show where a print statement is inappropriate i.e:

if f.show(): pass
if print(f): pass #raise exception
2 of 3
4

The __str__ method is being very careful to make sure everything is a str and so it returns a str.

The show method is relying on print to convert self.num and self.den to str implicitly. It displays the result as a side-effect, and returns None

print will insert a space between each parameter.

>>> str(3)+"/"+str(5)
'3/5'
>>> print(3,"/",5)
3 / 5

If you don't care about the extra spaces, there's really no reason not to use

def show(self):
    print(self)

perhaps the author thinks it's clearer not to do it that way.

Decoupling show and __str__ this way may also be surprising when you try to make a subclass. If the subclass overrides __str__, you would probably expect the change to be reflected in show too.

Find elsewhere
🌐
Scaler
scaler.com › home › topics › what is python __str__?
What is Python __str__? | Scaler Topics
June 11, 2024 - In this example, we have defined the python __str__ method and you can compare the results of this example from the previous example. Here, the __str__ method is defined already and when you call the __str__, str() and print() methods, the output we get is from the defined __str__ method.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-str-repr-functions
How To Use the __str__() and __repr__() Methods in Python | DigitalOcean
Learn Python’s str() and repr() methods in depth. Explore examples, best practices, and real-world tips for clarity and debugging.
Top answer
1 of 2
1

For this we can use enumerate to easily get the index number of a given element in a list, and with its second argument we can shift it to start from 1, we can use this to get

>>> question = 'Biggest city in England?'
>>> alternatives = ['Manchester', 'Liverpool', 'London']
>>> for i,v in enumerate(alternatives,1):
        print(f'{i} - {v}')

    
1 - Manchester
2 - Liverpool
3 - London
>>>     

Now lets change the previous loop into an appropriate list comprehension

>>> [f'{i} - {v}' for i,v in enumerate(alternatives,1)]
['1 - Manchester', '2 - Liverpool', '3 - London']
>>>

Now we use str.join to, well, join them together and remove the [] to make it into a generator expression while we are at it

>>> temp=', '.join(f'{i} - {v}' for i,v in enumerate(alternatives,1))
>>> temp
'1 - Manchester, 2 - Liverpool, 3 - London'
>>> 

now we got the 80% of it, lets go for the final touch

>>> f"{question} {temp}"
'Biggest city in England? 1 - Manchester, 2 - Liverpool, 3 - London'
>>> 

And we're done.

Also f-string can take almost any python expression, so we can make this into a one liner

>>> f"{question} { ', '.join(f'{i} - {v}' for i,v in enumerate(alternatives,1)) }"
'Biggest city in England? 1 - Manchester, 2 - Liverpool, 3 - London'
>>>      
2 of 2
1

You can try with __str__ as shown below (update the f-string with dashes and/or whitespaces instead of newlines to meet your needs):

>>> class MultipleChoice:
...     #Constructor
...     def __init__(self, question, alternatives, correct_answer):
...         self.question = question
...         self.alternatives = alternatives
...         self.correct_answer = correct_answer
...     def __str__(self):
...         return f'{self.question}\n' + '\n'.join(f'{i} {a}' for i, a in enumerate(self.alternatives,1))
... 
>>> question1 = MultipleChoice('What´s best?', ['Mac', 'PC'], 1)
>>> question2 = MultipleChoice('Biggest city in England?' , ['Manchester','Liverpool', 'London'], 3)
>>> 
>>> print(question1)
What´s best?
1 Mac
2 PC
>>> print(question2)
Biggest city in England?
1 Manchester
2 Liverpool
3 London
🌐
Educative
educative.io › answers › what-is-the-str-method-in-python
What is the __str__ method in Python?
The __str__ method in Python represents class objects as a string. It can be used as a debugging tool when the members of a class need to be checked.
Top answer
1 of 8
26

You created a Blog model. Once you migrate this, Django will create a table with "name" and "tagline" columns in your database.

If you want to interact with the database with the model, for example create an instance of the model and save it or retrieve the model from db,

def __str__(self):
    return self.name 

will come handy. Open the python interactive shell in your project's root folder via:

python manage.py shell

Then

from projectName.models import Blog 
Blog.objects.all() # will get you all the objects in "Blog" table

Also, when you look at the models in your admin panel, you will see your objects listed, with the name property.

The problem is, the return will look like this if you did not add that function:

<QuerySet [<Blog:>,<Blog:>,<Blog:>....]

So you will not know what those objects are. A better way to recognize those objects is retrieving them by one of its properties which you set it as name. This way you will get the result as follow:

 <QuerySet [<Blog:itsName>,<Blog:itsName>,<Blog:itsName>....]

If you want to test this out, run python manage.py shell and run:

from projectName.models import Blog

# The below will create and save an instance.
# It is a single step. Copy-paste multiple times.
Blog.objects.create(name="first",tagline="anything")
Blog.objects.all() # check out the result
2 of 8
18

The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this

Note: how objects are just plainly numbered

to this

.

Note: proper object names here

You could choose what to show in the admin panel, as per your choice. Be it a field value or a default value or something else.

🌐
Medium
medium.com › @btech.07 › str-method-add74b2760ae
__str__ method. The __str__ method in Python is a… | by Techie Ashu | Medium
December 4, 2024 - def __str__(self): return f"MyClass object is just to test" When you print an instance of MyClass, Python will use this method to get the string that represents the object.
🌐
AskPython
askpython.com › python › built-in-methods › python-str-function
Python str() Function - AskPython
July 12, 2022 - This output doesn’t help us because as a developer, there is no useful information about the object. Let’s implement the __str__() function. def __str__(self): return f'Emp::ID={self.id}, Name={self.name}' ... The python str() function is ...
🌐
Medium
annaikoki.medium.com › special-string-method-str-in-python-objects-and-how-to-use-it-19680af1d660
Special string method __str__ in Python objects and how to use it | by Anna Ikoki | Medium
January 30, 2023 - Here, what happens is the object calls the built-in string representation of an object using the built-in function object.__repr__()
🌐
Engineering LibreTexts
eng.libretexts.org › bookshelves › computer science › programming languages › think python - how to think like a computer scientist (downey) › 8: classes and methods
8.6: The __str__ Method - Engineering LibreTexts
August 1, 2021 - # inside class Time: def __str__(self): return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second) When you print an object, Python invokes the str method:
🌐
Leapcell
leapcell.io › blog › understanding-the-str-method-in-python
Understanding the `__str__` Method in Python | Leapcell
July 25, 2025 - The __str__ method is a special (or “magic”) method in Python used to define the “informal” or user-friendly string representation of an object. It is called when you use the built-in str() function or the print() function on an object. ...
🌐
Manning
livebook.manning.com › wiki › categories › python › __str__
Understanding the __str__ Method in Python
Another example is a class representing RGB colors, where the __str__ method is used to return a string representation of the color’s red, green, and blue components: class Color: def __init__(self, red, green, blue): self._red = red self._green = green self._blue = blue def __str__(self): return f"Color: R={self._red:d},G={self._green:d},B={self._blue:d}"
🌐
Greenteapress
greenteapress.com › thinkpython › html › book018.html
Chapter 17 Classes and methods
Buy this book at Amazon.com Chapter 17 Classes and methods17.1 Object-oriented features · Python is an object-oriented programming language, which means that it provides features that support object-oriented programming