Creating dynamic objects with dynamic constructor args

Discussion in 'Python' started by Greg Hoover, Mar 25, 2008.

  1. Greg Hoover

    Greg Hoover Guest

    I'd like to create objects on the fly from a pointer to the class
    using: instance = klass() But I need to be able to pass in variables
    to the __init__ method. I can recover the arguments using the
    inspect.argspec, but how do I call __init__ with a list of arguments
    and have them unpacked to the argument list rather than passed as a
    single object?

    ie. class T:
    def __init__(self, foo, bar):
    self.foo = foo
    self.bar = bar

    argspec = inspect.argspec(T.__init__)
    args = (1, 2)

    ??? how do you call T(args)?

    Thanks.
    Greg
    Greg Hoover, Mar 25, 2008
    #1
    1. Advertising

  2. Greg Hoover

    Robert Bossy Guest

    wrote:
    > I'd like to create objects on the fly from a pointer to the class
    > using: instance = klass() But I need to be able to pass in variables
    > to the __init__ method. I can recover the arguments using the
    > inspect.argspec, but how do I call __init__ with a list of arguments
    > and have them unpacked to the argument list rather than passed as a
    > single object?
    >
    > ie. class T:
    > def __init__(self, foo, bar):
    > self.foo = foo
    > self.bar = bar
    >
    > argspec = inspect.argspec(T.__init__)
    > args = (1, 2)
    >
    > ??? how do you call T(args)?
    >

    The star operator allows you to do this:
    T(*args)


    You also can use dict for keyword arguments using the double-star operator:

    class T(object):
    def __init__(self, foo=None, bar=None):
    self.foo = foo
    self.bar = bar

    kwargs = {'bar': 1, 'foo': 2}
    T(**kwargs)


    RB
    Robert Bossy, Mar 25, 2008
    #2
    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. Ken Varn
    Replies:
    2
    Views:
    624
    Ken Varn
    Jun 22, 2005
  2. Replies:
    3
    Views:
    490
    David Eppstein
    Sep 17, 2003
  3. Pierre Fortin

    args v. *args passed to: os.path.join()

    Pierre Fortin, Sep 18, 2004, in forum: Python
    Replies:
    2
    Views:
    686
    Pierre Fortin
    Sep 18, 2004
  4. er
    Replies:
    2
    Views:
    503
  5. Andrew Tomazos
    Replies:
    5
    Views:
    574
Loading...

Share This Page