How to replace constructor with factory method

Luis Zarrabeitia kyrie at uh.cu
Mon May 11 17:26:49 EDT 2009


On Monday 11 May 2009 04:39:41 pm rogeeff at gmail.com wrote:

> so o = A() instead being equivalent to:
>
> s = object()
> A.__init__(s)
> o = s

Actually, it would be more like this:

s = A.__new__(A)
if isinstance(s,A):
    A.__init__(s)
o = s

> o = my_factory_function( A )

You could tweak:
*) A's constructor (__new__) [keep in mind the 'insinstance' part]
*) A's initializer (changing the type, and so on... ugly, fragile and 
dangerous, don't ever do it!)
*) A's metaclass (the instantiation happens in the metaclass' __call__ method,
you could rewrite it to suit your needs, as in [1]
*) or, just use a method named A instead of the A class (as the 
multiprocessing.Queue function does)

I would use the 4th option. The fact that python classes are callable allows 
you to switch from instantiation to function calling without having to change 
the user's code.


[1] http://trucosos.crv.matcom.uh.cu/snippets/95/

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie



More information about the Python-list mailing list