Smart factory class

Discussion in 'Python' started by kramer31, Jan 24, 2008.

  1. kramer31

    kramer31 Guest

    Can anyone tell me if there is a way in python that I can implement a
    factory function which takes as input a string ClassName and returns
    an object of type ClassName?
     
    kramer31, Jan 24, 2008
    #1
    1. Advertising

  2. On Jan 24, 7:11 am, kramer31 <> wrote:
    > Can anyone tell me if there is a way in python that I can implement a
    > factory function which takes as input a string ClassName and returns
    > an object of type ClassName?


    >>> def mkobj(classname, ns=globals()): return ns[classname]()

    ...
    >>> class A: pass

    ...
    >>> mkobj('A')

    <__main__.A instance at 0x6bd28>
    >>>


    But why do you want to do this?

    --
    Arnaud
     
    Arnaud Delobelle, Jan 24, 2008
    #2
    1. Advertising

  3. En Thu, 24 Jan 2008 05:11:19 -0200, kramer31 <>
    escribió:

    > Can anyone tell me if there is a way in python that I can implement a
    > factory function which takes as input a string ClassName and returns
    > an object of type ClassName?


    def InstanceFactory(classname):
    cls = globals()[classname]
    return cls()

    If the class resides in a different module:

    def InstanceFactory(modulename, classname):
    if '.' in modulename:
    raise ValueError, "can't handle dotted modules yet"
    mod = __import__(modulename)
    cls = getattr(mod, classname]
    return cls()

    I suppose you get the names from a configuration file or something -
    usually it's better to just pass the class instead of the class name.

    --
    Gabriel Genellina
     
    Gabriel Genellina, Jan 24, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Medi Montaseri
    Replies:
    17
    Views:
    895
    Medi Montaseri
    Sep 3, 2003
  2. MotoK
    Replies:
    59
    Views:
    1,849
    Keith Thompson
    Sep 15, 2006
  3. Steven T. Hatton
    Replies:
    7
    Views:
    389
    Kai-Uwe Bux
    Nov 30, 2006
  4. C#
    Replies:
    4
    Views:
    420
  5. muswei

    Smart Pointers with Abstract Factory

    muswei, Dec 12, 2008, in forum: C Programming
    Replies:
    0
    Views:
    411
    muswei
    Dec 12, 2008
Loading...

Share This Page