[Tutor] __new__ over __init__
Peter Otten
__peter__ at web.de
Thu Sep 2 12:26:45 CEST 2010
Alan Gauld wrote:
> "Payal" <payal-tutor at scriptkitchen.com> wrote
>> b. What does type(_) mean?
>
> The _ refers to the last evaluated result, in this case the tuple
> (1,2).
> Its a shorthand trick, I think it only works in the interpreter, I
> don't like
> it and never use it, but many do. (FWIW Perl has a similar shortcut
> and Perl fans use it a lot!)
_ does indeed only work in interactive mode. It is handy when you evaluate
an expression and only then notice that you want to do something with the
result.
I added the type(_) line as an afterthought when I saw that the A instance
was indistinguishable from a tuple.
A more forward-thinking demo would have been
>>> class A(tuple):
... def __new__(cls, a, b):
... return tuple.__new__(cls, (a, b))
...
>>> a = A(1, 2)
>>> a
(1, 2)
>>> type(a)
<class '__main__.A'>
Peter
More information about the Tutor
mailing list