Simulating call of instance like a list or tuple
Andrew Bennetts
andrew-pythonlist at puzzling.org
Sun Jan 13 06:48:47 EST 2002
On Sun, Jan 13, 2002 at 12:33:52AM -0800, Brett Cannon wrote:
> First, thanks to everyone who replied to my post.
>
> It seems everyone is thinking that I want __repr__ or __str__, which is in
> the right vein, but not quite it. I want the same functionality, but I
> want to be able to return something other than a string. I don't think it
> exists outside of the built-in classes.
No, __repr__ *is* what you want.
First, let's be perfectly clear -- is this the functionality you are
referring to:
>>> l = [1,2,3]
>>> l
[1, 2, 3]
>>>
Yes?
Ok, now notice this:
>>> repr(l)
'[1, 2, 3]'
That's right, repr returns the string representation, so that printing the
value from repr:
>>> print repr(l)
[1, 2, 3]
is the same as evaluating the object interactively:
>>> l
[1, 2, 3]
You could also do:
>>> print l
[1, 2, 3]
Note that this isn't "calling" the list -- that would be "l()", which gives
this response:
>>> l()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object of type 'list' is not callable
Does this explain things more clearly? The point here is that the "[1, 2,
3]" you're seeing is not a list, it's the string representation of a list.
I think that's where you're getting confused.
I hope this has helped explain this for you. If not, please post an example
of where a list behaves differently, and we'll figure out where you (or we)
are getting confused.
-Andrew.
More information about the Python-list
mailing list