String Conversion in Python: When to Use __repr__ vs __str__
HTML-код
- Опубликовано: 20 сен 2024
- dbader.org/pyt... ► 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: dbader.org/pyt...
FREE COURSE - "5 Thoughts on Mastering Python" dbader.org/pyt...
PYTHON TRICKS: THE BOOK dbader.org/pyt...
SUBSCRIBE TO THIS CHANNEL: dbader.org/you...
* * *
► Python Developer MUGS, T-SHIRTS & MORE: nerdlettering.com
FREE Python Tutorials & News:
» Python Tutorials: dbader.org
» Python News on Twitter: / @dbader_org
» Weekly Tips for Pythonistas: dbader.org/new...
» Subscribe to this channel: dbader.org/you...
so far most clear & best tutorial about this topic on yt. You have made a great video with amazing effort.
Great video! Thanks for your effort on making these videos!!!
You're welcome! :-)
I like '...the Pythonic way to do this...' xD
import this
Amazing content, first of all very informative, second your voice and delivery are amazing. Thank you for this video.
Great tutorials overrall. 10/10.
By the way, I just wanted to make a note. This probably came afterwards, considering how old the video is.
A simple solution is: __repr__ = __str__.
However, I'd be interested to read any feedback on this solution. Thank you
Could you Please explain
self = self
I would really like an explanation of this as well
Me too
here's some helpfull link :
pyformat.info/
a lit explanation on old format python used 'value' % (value)
in new format can be used as 'value'.format(value)
if used self on return value on format need to use self=self to represent the self
correct me if i'm wrong
The left hand side of "self" is the local variable passed into the return "{self.__class}...." , the right hand side of "self" is the actual self received from the function __repr__(self) , which represents the actual object itself.
TsungJui Wang why is that necessary?
Thank you for the video. I am grateful for your time and contribution. Kind regards, Akira.
Thanks for insightful video. Got it checked.
Great insight I had been struggling to comprehend this subject for quite some time ,this video helped a lot
This explanation is better than I found in paid course.
I understand what you mean in the different use cases for both methods, but may I ask, why is it like that?. Why did the communitty agree that str is better for readability and repr for 'debugging'
very elegantly explained, thank you!
Thx from Brazil!!
I'm in love with this channel ❤
Hi there, great video! What do you mean by inspecting the car object? 3:52
Very helpful explanation!
I'm glad you liked it!
pretty explanatory and useful, thanks for this tutorial
thank your for your efforts. Could you tell me the name of the package, which shows method details as you write?
press ctrl and click on the method name if you use pycharm
Watching this tutorial could literally pay you money in the future LOL😆
this video helps me a lot 😍💚 thanks a lot man
Your python terminal looks cool with the auto-complete, etc. Are you using some third party software for that?
Installed and it works great. Thanks. Also, in love with your whole series!
Daniel is using bpython for the interpreter.
Great video(s). But you should have quotes around the {self.color}, no? So that repr(my_car) outputs: Car('red', 37281)
No
Thank you! It was very clear
You're welcome!
what program are you using for python?
Great job, I have just a small question: what should I do if i want to get car("red","37281"), the diffrence is the quotation. Thank youuuuu
Really helpful and concise. Thanks
You're welcome!
great video
Came straight to the comment section to post something about “Dunder Mifflin… I know why I never learn shit
great explanation
Thanks!
Note that you can add `!r` to the format string, so `{self.color!r}` and you get the repr of the child object for free!
Thanks for sharing! :-)
Say you have a child class ElectricCar, can you make str(myElectricCar) print out the same str as the parent class?
So finally I understood that developers are not humans :D
thanks!
bro i love you
Hi! What font are you using in this video?
Does repr mean representation? So you could put in almost like a doc string to help define the class?
Yes, 'repr' refers to representation.
As for your second question: not quite. While in principle you could place a string or a docstring within ___repr___ , that's not its pythonic/intended purpose. As mentioned in the video, ___repr___ needs to provide an unambiguous description of the *object*; a docstring is simply human readable description of the class. Moreover, docstrings, if they are provided, are already handled by the ___doc___ attribute. You can read it more about it here: www.python.org/dev/peps/pep-0257/
Hello, I have a question about extracting values from a dictionary array embedded in a csv data file. A snapshot of the dictionary looks like this:
{"geodesic":false, "type":"Point", "coordinates": [35.9, 24.9]}
How can I extract the coordinates from the dictionary and save them in separate column or export it to a csv file? I have had difficulty in getting this done. Appreciate your help. Thank you!
which editor is that, looks cool
I mainly use Sublime Text 3
man how do u change font and theme for jango ...///
thank you
You're very welcome!
can __str__ and __repr__ return more than one string??? and if yes how
im seven months late but to my knowledge: No. I mean, if you want to print a bunch of messages when the method is called, you can do that, because there's nothing special about dunder methods except that they're automatically called by different functions. You can return a tuple of strings if you'd like, but why?
def __str__(self):
print('ran dunder str')
return (self.__class__.__name__, 'another string', 'third string')
Are you using PyCharm?
Python Shell
Yeah
What text editor it is?
7:06
:o did RUclips finally added shortcut "k" to pause/continue or was I retarded?
For us JAVA folks, __str__ is "toString". Call me old fashion, but prefer to call it a "to string method" and not "dunder string". :-)
Thanks for sharing! :-)
For real, when I first heard someone say "dunder" I thought they flat out made a mistake.
dunder mifflin
Not a simple explanation
human consumption? youre not gunna eat the code lmao