What is the mechanism behide?

Mark McEahern marklists at mceahern.com
Tue Sep 24 18:31:31 CEST 2002


> I'm studying the singleton pattern, there are something I don't
> understand in the sample code below:
[snip]
>     I'm puzzled that what is behide the statement "print x" ?

This is a more straightforward sample to cut your teeth on, imho:

>>> class foo:
...     def __str__(self):
...             print "calling __str__"
...             return "whatever we like"
...     def __repr__(self):
...             print "calling __repr__"
...             return "something different"
...
>>> f = foo()
>>> print f
 calling __str__
whatever we like
>>> print `f`
calling __repr__
something different
>>>

So __str__ simply allows you to override what happens when str() is called
on an instance of your class.  str() is what print calls, I believe.

__repr__ allows you to override what happens when repr() is called.  The
backticks (e.g., ``) are equivalent to repr().

You might want to lookup print, __str__, __repr__, str(), and repr() in the
docs.

I don't have the patience to decode the OnlyOne stuff.  Perhaps someone else
does.

Cheers,

// m





More information about the Python-list mailing list