Using getattr() to construct function objects from strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def color_red(): | |
return 'I am red' | |
def color_green(): | |
return 'I am green' | |
def color_blue(): | |
return 'I am blue' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# Demo of constructing function object from strings | |
from __future__ import print_function | |
# module where the functions are defined | |
import funcs | |
# entry point when executed | |
if __name__=='__main__': | |
colors = ['red','blue','green'] | |
for color in colors: | |
funcname = 'color_{0:s}'.format(color) | |
print(getattr(funcs,funcname)()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment