String Conversion in Python: When to Use __repr__ vs __str__

Publié le: 07 février 2017
sur la chaîne: Real Python
81,188
1.9k

https://dbader.org/python-tricks ► String conversion in Python classes and other advanced OOP techniques

When you define a custom class in Python and then try to print one of its instances to the console (or inspect it in an interpreter session) you get a relatively unsatisfying result. The default "to string" conversion behavior is basic and lacking in detail.

By default all you get is a string containing the class name and the `id` of the object instance (which is the object's memory address in CPython). That's better than *nothing*, but it's also not very useful.

The solution here is adding the `__str__` and `__repr__` "dunder" methods (some call them "magic methods") to your class.

They are the Pythonic way to control how objects are converted to strings in different situations.

In this tutorial video I'll do a deep dive on how Python's to-string conversion works and how you can add it to your own custom classes.

I'll walk you through the _str_ and _repr_ methods, when to use each, and some tips on how to use them in real world scenarios.

Just remember:

The result of `__str__` should be readable.

The result of `__repr__` should be unambiguous.

Always add a `__repr__` to your classes. The default implementation for `__str__` just calls `__repr__`, so you get the best of both worlds.

To learn how to use the full potential of Python check out "Python Tricks: The Book" at the link below: https://dbader.org/pytricks-book


FREE COURSE – "5 Thoughts on Mastering Python" https://dbader.org/python-mastery

PYTHON TRICKS: THE BOOK https://dbader.org/pytricks-book

SUBSCRIBE TO THIS CHANNEL: https://dbader.org/youtube

* *

► Python Developer MUGS, T-SHIRTS & MORE: https://nerdlettering.com

FREE Python Tutorials & News:
» Python Tutorials: https://dbader.org
» Python News on Twitter:   / @dbader_org  
» Weekly Tips for Pythonistas: https://dbader.org/newsletter
» Subscribe to this channel: https://dbader.org/youtube


Sur cette page du site, vous pouvez voir la vidéo en ligne String Conversion in Python: When to Use __repr__ vs __str__ durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur Real Python 07 février 2017, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 81,188 fois et il a aimé 1.9 mille téléspectateurs. Bon visionnage!