Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Creating dynamic objects with dynamic constructor args

Reply
Thread Tools

Creating dynamic objects with dynamic constructor args

 
 
Greg Hoover
Guest
Posts: n/a
 
      03-25-2008
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

 
Reply With Quote
 
 
 
 
Robert Bossy
Guest
Posts: n/a
 
      03-25-2008
http://www.velocityreviews.com/forums/(E-Mail Removed) 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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
forwarding Args&&... vs forwarding Args... Andrew Tomazos C++ 5 01-05-2012 11:15 PM
C++0x -- fun(Args&...) and fun(Args const&...) er C++ 2 12-20-2010 07:52 PM
Is there a class or method to construct url args or extract url args? Ken Varn ASP .Net 2 06-22-2005 12:26 PM
args v. *args passed to: os.path.join() Pierre Fortin Python 2 09-18-2004 06:59 PM
When passing functions as args,how to pass extra args for passed function? python@sarcastic-horse.com Python 3 09-17-2003 12:25 AM



Advertisments