How to use a variable as function name in Python

前端 未结 6 1947
庸人自扰
庸人自扰 2020-12-01 16:17

Would it be possible to use a variable as a function name in python? For example:

list = [one, two, three]
for item in list:
    def item():
         some_st         


        
6条回答
  •  孤街浪徒
    2020-12-01 17:06

    Here is a workaround wrapped in a class. It uses a dictionary for the mapping:

    class function_class:
        def __init__(self,fCase):
            fDic = {'A':self.A,         # mapping: string --> variable = function name
                    'B':self.B,
                    'C':self.C}
            self.fActive = fDic[fCase]
        def A(self): print('here runs function A')
        def B(self): print('here runs function B')
        def C(self): print('here runs function C')
        def run_function(self):
            self.fActive()
    
    #---- main ----------        
    fList = ['A','B','C']              # list with the function names as strings
    for f in fList:                    # run through the list
        g = function_class(f)
        g.run_function()
    

    The output is:

    here runs function A
    here runs function B
    here runs function C
    

提交回复
热议问题