Class introspection and dynamically determining function arguments

Nick Coghlan ncoghlan at iinet.net.au
Thu Jan 20 07:27:05 EST 2005


Diez B. Roggisch wrote:
> Mark English wrote:
> As youself already mentioned that maybe you have to impose certain
> prerequisites, you maybe want to extend this to the point where for each
> class you want to make dynamically instantiatable you need some
> declaration. This of course depends on your desired application - whatfor
> is it planned? 

If this only has to work for classes created for the purpose (rather than for an 
arbitrary class):

Py> class Buildable(object):
...   __slots__ = ["x", "y"]
...   def __init__(self, **kwds):
...     super(Buildable, self).__init__(self, **kwds)
...     for attr in Buildable.__slots__:
...       setattr(self, attr, kwds[attr])
...
Py> b = Buildable(x = 1 , y = 2)
Py> b.x
1
Py> b.y
2

(Note that you don't *have* to use slots, you can use a non-special class 
attribute if you don't want the other side effects)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list