How to replace constructor with factory method

R

rogeeff

Hi,

Just wonder if it's possible in Python.

what I want is to tweak an existing Python class A with no
constructor, so that A() results in fuctory method call?

so o = A() instead being equivalent to:

s = object()
A.__init__(s)
o = s

becomes:

o = my_factory_function( A )

Thanks,

Gennadiy
 
L

Luis Zarrabeitia

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/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,291
Messages
2,571,453
Members
48,137
Latest member
IndiraMcCo

Latest Threads

Top