newbie: question about "__repr__"

Discussion in 'Python' started by chenyu, Nov 6, 2003.

  1. chenyu

    chenyu Guest

    Hi,
    I have read others' code for study, and found one built-in function
    "__repr__". Could anyone give me an simple example for explaining
    "when and how" to use it.


    Thank you for your attention.
    kind regards/chenyu
    chenyu, Nov 6, 2003
    #1
    1. Advertising

  2. chenyu

    John Roth Guest

    "chenyu" <> wrote in message
    news:...
    > Hi,
    > I have read others' code for study, and found one built-in function
    > "__repr__". Could anyone give me an simple example for explaining
    > "when and how" to use it.


    __repr__ is the "magic method" that is used by the repr() built-in
    function. It's similar to the str() built-in, but they serve different
    purposes. str() is for when you want a human-readable representation,
    repr() is for when you want more detail; most objects try to make whatever
    repr() puts out round-trip through the exec statement and eval() functions.
    This isn't always possible, but that's the difference between the two.

    Both repr() and str() will use the other entry point if their prefered
    magic method isn't availible.

    John Roth
    >
    >
    > Thank you for your attention.
    > kind regards/chenyu
    John Roth, Nov 6, 2003
    #2
    1. Advertising

  3. "chenyu" <> wrote in message
    news:...
    > Hi,
    > I have read others' code for study, and found one built-in function
    > "__repr__". Could anyone give me an simple example for explaining
    > "when and how" to use it.


    The customary use of __repr__ is for it to return a string that can be
    passed to eval()
    and re-create the object. So for a class 'foo' that takes one string in its
    __init__, __repr__
    might return "foo('astring')".
    George Kinney, Nov 6, 2003
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jim Newton

    how to use __str__ and __repr__?

    Jim Newton, Jun 7, 2004, in forum: Python
    Replies:
    15
    Views:
    549
    Peter Maas
    Jun 9, 2004
  2. Dan Sommers
    Replies:
    3
    Views:
    302
    Serge Orlov
    Feb 19, 2005
  3. could ildg
    Replies:
    2
    Views:
    357
    Greg Ewing
    Apr 4, 2005
  4. Jan Danielsson

    FAQ: __str__ vs __repr__

    Jan Danielsson, Jun 15, 2005, in forum: Python
    Replies:
    15
    Views:
    731
    Skip Montanaro
    Jun 21, 2005
  5. Ben Finney

    Rich __repr__

    Ben Finney, Oct 31, 2005, in forum: Python
    Replies:
    7
    Views:
    377
    Donn Cave
    Nov 3, 2005
Loading...

Share This Page