matching keyword arguments to specific methods
Donnal Walter
donnalcwalter at yahoo.com
Mon Jan 27 17:29:59 EST 2003
Is there a better Python idiom than the following code for calling a method
by name if and only if the method exists?
if key in dir(self):
self.__class__.__dict__[key](self, kw[key])
What I want to do is handle keyword arguments with methods that have the
same name as the keywords, something like this:
class MyBase(object):
def __init__(self, **kw):
for i in kw:
if i in dir(self):
self.__class__.__dict__[i](self, kw[i])
class MyTest1(MyBase):
def default(self, val):
# other processing here
print val
def choices(self, val):
# other processing here
for i in val:
print i
class MyTest2(MyBase):
def limits(self, val):
# other processing here
for i in val:
print i
x = MyTest1(default='hello', choices = ('hi', 'hello', 'greetings'))
y = MyTest2(default='100', limits=(0, 1000))
Thanks,
Donnal Walter
Arkansas Children's Hospital
More information about the Python-list
mailing list