newbie: question about "__repr__"

C

chenyu

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
 
J

John Roth

chenyu said:
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
 
G

George Kinney

chenyu said:
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')".
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,539
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top