dynamic path to a method ???
Emile van Sebille
emile at fenx.com
Fri Jul 5 20:40:37 EDT 2002
Roger Ineichen
> Can anybody tell me how I can construct a dynamic path to a method in
> an other python class?
>
> my situation is:
> I get the classname, methodname and attributes by a dynamic form. They
> are strings and the names and attributes are dynamic. I do a iteration
> over the request an split the names and attributes.
> Example after iteration over the request:
>
> class (instance) = 'personManager'
> method = 'addPerson(firstname='', lastname='')'
> attribute1, firstname = 'max'
> attribute2, lastname = 'miller'
>
> how can I construct a dynamic path like:
> personManager.addPerson( firstname='max', lastname='miller')
#So, you have a class with a method something like:
class personManager:
def __init__(self): pass
def addPerson(self, firstname='', lastname=''):
self.firstname = firstname
self.lastname = lastname
#and you end up with strings in variables like:
classvar = 'personManager'
method = 'addPerson'
attribute1 = "firstname = 'max'"
attribute2 = "lastname = 'miller'"
# then, put attributes 1 & 2 into a dict:
kwargs = {}
for k,v in [x.split(" = ") for x in [attribute1, attribute2]]:
kwargs[k] = v
# create an instance
instance = globals()[classvar]()
# call the method
getattr(instance, method)(**kwargs)
# and take a look
print instance
print instance.firstname
print instance.lastname
HTH,
--
Emile van Sebille
emile at fenx.com
---------
More information about the Python-list
mailing list