variables - How to dynamically call a method in python? -


i call object method dinamically.

the variable "methodwanted" contains method want execute, variable "objecttoapply" contains object. code far is:

methodwanted=".children()"  print eval(str(objecttoapply)+methodwanted) 

but following error:

exception executing script   file "<string>", line 1     <pos 164243664 childindex: 6 lvl: 5>.children()     ^ syntaxerror: invalid syntax 

i tried without str() wrapping object, "cant use + str , object types" error.

when not dinamically, can do:

objecttoapply.children() 

and desired result.

how dinamically?

methods attributes, use getattr() retrieve 1 dynamically:

methodwanted = 'children'  getattr(objecttoapply, methodwanted)() 

note method name children, not .children(). don't confuse syntax name here. getattr() returns method object, still need call (jusing ()).


Comments

Popular posts from this blog

javascript - JS causing window size to be bigger than necessary - Dropdown bug -

How to mention the localhost in android -

php - Calling a template part from a post -