FAQ
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

Search Discussions

  • Chris Rebert at May 11, 2009 at 9:08 pm

    On Mon, May 11, 2009 at 1:39 PM, wrote:
    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 )
    I believe you'd need to override __new__ for that.
    Docs on __new__: http://docs.python.org/reference/datamodel.html#object.__new__

    Cheers,
    Chris
  • Luis Zarrabeitia at May 11, 2009 at 9:26 pm

    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

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedMay 11, '09 at 8:39p
activeMay 11, '09 at 9:26p
posts3
users3
websitepython.org

People

Translate

site design / logo © 2022 Grokbase