[Tutor] __new__ over __init__

Alan Gauld alan.gauld at btinternet.com
Wed Sep 1 10:14:50 CEST 2010


"Payal" <payal-tutor at scriptkitchen.com> wrote

>> >>> class A(tuple):
>> ...     def __new__(cls, a, b):
>> ...             return tuple.__new__(cls, (a, b))

> a. I have seen this cls before, what does it mean?

It is an abbreviation for class. The first parameter to new() must be 
a refernce to the class.
It is similar to self in an instance method, where the first parameter 
is a reference
to the instance.


> 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!)

Try:
>>> 5+5
10
>>> A = 1+2
>>> print _
10
>>> A
3
>>> print _
3

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list