I have a list of functions... e.g.
def filter_bunnies(pets): ...
def filter_turtles(pets): ...
def filter_narwhals(pets): ...
Is there a way to call these functions by using a string representing their name?
e.g.
'filter_bunnies', 'filter_turtles', 'filter_narwhals'
Add self. initialize() to myfunc() , this should do what you are looking for. class MyClass(object): def __init__(self): pass def initialize(self): print("I'm doing some initialization") def myfunc(self): self. initialize() print("This is myfunc()!")
Python's built-in exec() executes the Python code you pass as a string or executable object argument. This is called dynamic execution because, in contrast to normal static Python code, you can generate code and execute it at runtime. This way, you can run programmatically-created Python code.
Dynamic function calls are useful when you want to alter program flow according to changing circumstances. We might want our script to behave differently according to a parameter set in a URL's query string, for example. We can extract the value of this parameter and use it to call one of a number of functions.
Passing arguments to the dynamic function is straight forward. We simply can make solve_for() accept *args and **kwargs then pass that to func() . Of course, you will need to handle the arguments in the function that will be called.
Are your function a part of an object? If so you could use getattr
function:
>> class A:
def filter_bunnies(self, pets):
print('bunnies')
>>> getattr(A(), 'filter_bunnies')(1)
bunnies
Yes, you can use:
globals()['filter_bunnies']()
to call 'filter_bunnies'.
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