If I have an object and a method name in a string, how can I call the method?
class Foo: def bar1(self): print 1 def bar2(self): print 2 def callMethod(o, name): ??? f = Foo() callMethod(f, "bar1")
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.
To do this in Python you have to access the global namespace. Python makes you do this explicitly where PHP is implicit. In this example we use the globals() function to access the global namespace. globals() returns a dictionary that includes area as a key and the value is a reference to the area() function.
Use the built-in getattr()
function:
class Foo: def bar1(self): print(1) def bar2(self): print(2) def call_method(o, name): return getattr(o, name)() f = Foo() call_method(f, "bar1") # prints 1
You can also use setattr()
for setting class attributes by names.
I had similar question, wanted to call instance method by reference. Here are funny things I found:
instance_of_foo=Foo() method_ref=getattr(Foo, 'bar') method_ref(instance_of_foo) # instance_of_foo becomes self instance_method_ref=getattr(instance_of_foo, 'bar') instance_method_ref() # instance_of_foo already bound into reference
Python is amazing!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With