Simulating call of instance like a list or tuple

Peter Hansen peter at engcorp.com
Sat Jan 12 10:28:57 EST 2002


Brett Cannon wrote:
> 
> With Python 2.2's wonderful ability of subclassing built-ins, I began to
> wonder if there was a way to call an instance like a list or tuple, but
> without subclassing them.
> 
> In other words, have a class named foo with an instance called bar.  Now,
> call bar like:
> >>> bar
> and have  it return something, just like how calling a list or  tuple like
> that returned the list or  tuple value.  I can't find any special methods
> that allow you to do that.  Does that exist, or is that just one of the
> things that still separates built-ins and user-defined objects?

Do you mean __repr__() ?  If you override that in the class definition
you should get what you want.

>>> class A:
...   def __repr__(self):
...     return "I'm like a list!"
...
>>> a = A()
>>> a
I'm like a list!

-Peter



More information about the Python-list mailing list