How To Dynamically Call A Method In Python?
I would like to call an object method dynamically. The variable 'MethodWanted' contains the method I want to execute, the variable 'ObjectToApply' contains the object. My code so f
Solution 1:
Methods are just attributes, so use getattr()
to retrieve one dynamically:
MethodWanted = 'children'getattr(ObjectToApply, MethodWanted)()
Note that the method name is children
, not .children()
. Don't confuse syntax with the name here. getattr()
returns just the method object, you still need to call it (jusing ()
).
Post a Comment for "How To Dynamically Call A Method In Python?"