Spot any errors? let me know, but Unleash your pedant politely please.

Wednesday 27 May 2009

Python : Using **arg and setattr to create instance variables at runtime

I found that I need the generic/extendable **args, but I also needed those args easily visible to a method in a subclass. Initially I just passed the **args dctionary into a named parameter, but that seemed messy when I actually came to use it. Plus I need this usable by (even) less able programmers.

Here's in essence what I've done:
>>> class A(object):
... def __init__(self, **args):
... for key,value in args.iteritems():
... setattr(self,key,value)
...
>>> a=A(first = 1, second = 2, name="Monty")
>>> a.first
1
>>> a.second
2
>>> a.name
'Monty'

There's a little more to it. I have checks against the existing names in case I overwrite something, for example.

No comments:

Post a Comment