Creating dynamic objects with dynamic constructor args

G

Greg Hoover

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
 
R

Robert Bossy

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
 

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
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top