Calling a constructor by reference

exarkun at divmod.com exarkun at divmod.com
Thu Oct 7 09:54:04 EDT 2004


On 07 Oct 2004 06:53:06 -0700, Edwin Young <edwin at bathysphere.org> wrote:
>
> Hi,
> 
> I know there must be a way to do this but the correct syntax eludes me.
> 
> I want to write a method which I can pass different types to and have
> it construct them.
> 
> I tried this:
> 
> >>>
> class X:
>     def __init__(self):
>         pass
> 
> def make_thing(type,*args):
>     return type(args)
> 
> x = X()
> y = make_thing(X)
> 
> print x, y 
> >>>
> 
> But get 'TypeError: __init__() takes exactly 1 argument (2
> given)'. Presumably X is treated as an unbound instance method?
> 
> Also, the types I want to create inherit from an old-style class in a
> package, so I don't think I can make X a new-style class (if that's
> relevant).
> 
> How should I go about this?

  You're closer than you think, although some of your terminology is a bit confused.  Try this definition of make_thing instead:

    def make_thing(type, *args):
        return type(*args)

  Of course, an even simpler definition is possible:

    make_thing = apply

  And this version even supports passing arguments by keyword ;)

  A note about terms: in your example above, X is a class object.  X.__init__ is an unbound method, the initialized (not the constructor).  Calling a class object is a shortcut for calling the constructor and then calling the initializer.

  Jp




More information about the Python-list mailing list