python - Why is __init__() always called after __new__()? -


i'm trying streamline 1 of classes , have introduced functionality in same style flyweight design pattern.

however, i'm bit confused why __init__ called after __new__. wasn't expecting this. can tell me why happening , how can implement functionality otherwise? (apart putting implementation __new__ feels quite hacky.)

here's example:

class a(object):     _dict = dict()      def __new__(cls):         if 'key' in a._dict:             print "exists"             return a._dict['key']         else:             print "new"             return super(a, cls).__new__(cls)      def __init__(self):         print "init"         a._dict['key'] = self         print ""  a1 = a() a2 = a() a3 = a() 

outputs:

new init  exists init  exists init 

why?

use __new__ when need control creation of new instance. use __init__ when need control initialization of new instance.

__new__ first step of instance creation. it's called first, , responsible returning new instance of class. in contrast, __init__ doesn't return anything; it's responsible initializing instance after it's been created.

in general, shouldn't need override __new__ unless you're subclassing immutable type str, int, unicode or tuple.

from: http://mail.python.org/pipermail/tutor/2008-april/061426.html

you should consider trying done factory , that's best way it. using __new__ not clean solution please consider usage of factory. here have a factory example.


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -