tutor  

Re: [Tutor] __new__ over __init__

Alan Gauld
Wed, 01 Sep 2010 01:17:02 -0700

"Payal" <payal-tu...@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/


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor