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...

Комментарии • 81

  • @Rudra-go6us
    @Rudra-go6us 3 года назад +2

    so far most clear & best tutorial about this topic on yt. You have made a great video with amazing effort.

  • @jingyuchang1885
    @jingyuchang1885 6 лет назад +9

    Great video! Thanks for your effort on making these videos!!!

  • @matiturock
    @matiturock 4 года назад +10

    I like '...the Pythonic way to do this...' xD

  • @alexpeak1008
    @alexpeak1008 3 года назад +1

    Amazing content, first of all very informative, second your voice and delivery are amazing. Thank you for this video.

  • @BijouBakson
    @BijouBakson Год назад

    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

  • @kishorekumar2769
    @kishorekumar2769 6 лет назад +40

    Could you Please explain
    self = self

    • @maglcman
      @maglcman 6 лет назад +3

      I would really like an explanation of this as well

    • @KevinJohnson-wk1bx
      @KevinJohnson-wk1bx 6 лет назад +2

      Me too

    • @peterwilliam192
      @peterwilliam192 6 лет назад

      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

    • @tsungjuiwang7031
      @tsungjuiwang7031 6 лет назад +15

      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.

    • @nclt1978
      @nclt1978 6 лет назад +10

      TsungJui Wang why is that necessary?

  • @akira_asahi
    @akira_asahi 2 года назад

    Thank you for the video. I am grateful for your time and contribution. Kind regards, Akira.

  • @iammayurn
    @iammayurn 2 года назад

    Thanks for insightful video. Got it checked.

  • @nazrulhassan6310
    @nazrulhassan6310 4 года назад +3

    Great insight I had been struggling to comprehend this subject for quite some time ,this video helped a lot

  • @TechMarketer
    @TechMarketer 3 года назад

    This explanation is better than I found in paid course.

  • @diegovegacruz3213
    @diegovegacruz3213 2 года назад

    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'

  • @junyihou4736
    @junyihou4736 4 года назад

    very elegantly explained, thank you!

  • @igorsantos-qj3zd
    @igorsantos-qj3zd 3 года назад

    Thx from Brazil!!

  • @SidTheBot
    @SidTheBot 3 года назад

    I'm in love with this channel ❤

  • @KevinJohnson-wk1bx
    @KevinJohnson-wk1bx 6 лет назад +1

    Hi there, great video! What do you mean by inspecting the car object? 3:52

  • @rogerwang21
    @rogerwang21 5 лет назад +2

    Very helpful explanation!

  • @carlosdelamorenacoco8715
    @carlosdelamorenacoco8715 3 года назад

    pretty explanatory and useful, thanks for this tutorial

  • @colonel666
    @colonel666 5 лет назад +3

    thank your for your efforts. Could you tell me the name of the package, which shows method details as you write?

    • @debojyotisarkar3008
      @debojyotisarkar3008 4 года назад

      press ctrl and click on the method name if you use pycharm

  • @zaph254
    @zaph254 Год назад

    Watching this tutorial could literally pay you money in the future LOL😆

  • @kunalsoni7681
    @kunalsoni7681 3 года назад

    this video helps me a lot 😍💚 thanks a lot man

  • @SaurabhAriyan
    @SaurabhAriyan 7 лет назад +1

    Your python terminal looks cool with the auto-complete, etc. Are you using some third party software for that?

    • @SaurabhAriyan
      @SaurabhAriyan 7 лет назад

      Installed and it works great. Thanks. Also, in love with your whole series!

    • @y0danz
      @y0danz 6 лет назад +1

      Daniel is using bpython for the interpreter.

  • @ropro9817
    @ropro9817 3 года назад

    Great video(s). But you should have quotes around the {self.color}, no? So that repr(my_car) outputs: Car('red', 37281)

  • @horse_butt
    @horse_butt 5 лет назад +1

    Thank you! It was very clear

  • @gabrielamos2638
    @gabrielamos2638 2 года назад

    what program are you using for python?

  • @anas.2k866
    @anas.2k866 7 лет назад

    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

  • @donha475
    @donha475 5 лет назад

    Really helpful and concise. Thanks

  • @sabririhab9383
    @sabririhab9383 2 года назад

    great video

  • @lonelylosersclub8453
    @lonelylosersclub8453 2 года назад

    Came straight to the comment section to post something about “Dunder Mifflin… I know why I never learn shit

  • @pythonlearning1932
    @pythonlearning1932 4 года назад

    great explanation

  • @mikeafter5
    @mikeafter5 3 года назад

    Thanks!

  • @WayneWerner
    @WayneWerner 7 лет назад +5

    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!

  • @petrockspiracy3120
    @petrockspiracy3120 6 лет назад

    Say you have a child class ElectricCar, can you make str(myElectricCar) print out the same str as the parent class?

  • @sajoloudy
    @sajoloudy 3 года назад

    So finally I understood that developers are not humans :D

  • @DragonRazor9283
    @DragonRazor9283 3 года назад

    thanks!

  • @koopstakh301
    @koopstakh301 2 года назад

    bro i love you

  • @danebaird8292
    @danebaird8292 4 года назад

    Hi! What font are you using in this video?

  • @382946rthu
    @382946rthu 7 лет назад

    Does repr mean representation? So you could put in almost like a doc string to help define the class?

    • @burnere633
      @burnere633 7 лет назад +2

      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/

  • @gjubbar
    @gjubbar 5 лет назад

    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!

  • @3deoskill
    @3deoskill 5 лет назад +1

    which editor is that, looks cool

    • @realpython
      @realpython  5 лет назад +1

      I mainly use Sublime Text 3

  • @Tipsy_Nomad
    @Tipsy_Nomad 6 лет назад

    man how do u change font and theme for jango ...///

  • @waex7089
    @waex7089 5 лет назад +1

    thank you

  • @harshvardhanpathak3461
    @harshvardhanpathak3461 6 лет назад

    can __str__ and __repr__ return more than one string??? and if yes how

    • @thegamecracks1317
      @thegamecracks1317 5 лет назад +1

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

  • @createdbyjulius6133
    @createdbyjulius6133 4 года назад

    Are you using PyCharm?

    • @kotare86
      @kotare86 4 года назад

      Python Shell

  • @rau149
    @rau149 2 года назад

    Yeah

  • @midhileshmomidi2434
    @midhileshmomidi2434 4 года назад

    What text editor it is?

  • @diegovegacruz3213
    @diegovegacruz3213 2 года назад

    7:06

  • @jjjj-ms1ln
    @jjjj-ms1ln 5 лет назад +1

    :o did RUclips finally added shortcut "k" to pause/continue or was I retarded?

  • @andrewwolan4395
    @andrewwolan4395 6 лет назад +2

    For us JAVA folks, __str__ is "toString". Call me old fashion, but prefer to call it a "to string method" and not "dunder string". :-)

    • @realpython
      @realpython  6 лет назад

      Thanks for sharing! :-)

    • @liquidred257
      @liquidred257 3 года назад

      For real, when I first heard someone say "dunder" I thought they flat out made a mistake.

  • @Geobaums
    @Geobaums 4 года назад

    dunder mifflin

  • @Abhhijitviktor
    @Abhhijitviktor 3 года назад

    Not a simple explanation

  • @CameronNoakes
    @CameronNoakes 3 года назад

    human consumption? youre not gunna eat the code lmao