Simulating call of instance like a list or tuple

Justin Sheehy justin at iago.org
Sat Jan 12 09:39:52 EST 2002


Brett Cannon <bac at OCF.Berkeley.EDU> writes:

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

Lists and tuples aren't callable.  I'm guessing that what you really
mean is what you see when you evaluate a list or tuple at the
interactive Python prompt.

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

If my guess about what you really want is correct, see the __repr__
special method at
http://python.sourceforge.net/devel-docs/ref/customization.html

Quick example:

>>> class WithRepr:
...   def __init__(self, v):
...     self.v = v
...   def __repr__(self):
...     return 'WithRepr(%s)' % self.v
...
>>> a = WithRepr(1492)
>>> a
WithRepr(1492)
>>>

-Justin

 





More information about the Python-list mailing list