__init__ function problem

Gabriel Genellina gagsl-py at yahoo.com.ar
Wed Nov 8 02:25:06 CET 2006

At Tuesday 7/11/2006 21:47, Jia Lu wrote:

> > In Python, the real constructor is called __new__, >
> > Carl Banks
>But the code below won't invoke __new__:

Is this a question, or just for making things more and more confusing 
to beginners?

>class Test:
>     def __new__(self, value):
>         print "__new__",value

For old-style classes __new__ is not used. On new-style classes it's 
used mostly for dealing with immutable objects. The code should be:

class NewStyle(object):
     "A new style class inherits from object in some way"
     def __new__(cls, value):
         print "NewStyle.__new__",value
         return super(NewStyle, cls).__new__(cls, value)
         # return object.__new__(cls, value) for lazy people

     def __init__(self, value):
         print "NewStyle.__init__",value

class OldStyle:
     "An old style class does not inherit from object"
     def __init__(self, value):
         print "OldStyle.__init__",value

n = NewStyle(1)
o = OldStyle(2)

Gabriel Genellina
Softlab SRL 

Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar

More information about the Python-list mailing list