Python透過函式名呼叫函式的幾種場景

Python探索牛發表於2024-04-13

除了執行系統命令外,我們有時還需要動態地執行一些python程式碼,有經驗的朋友就會知道可以使用內建函式eval實現這一需求,如eval("print(__file__)"),這還是比較簡單的。

但如果要動態執行一個函式,講的資料就會少一點,這次就要看這個需求該如何實現。

一、透過eval實現

1 透過eval呼叫同一個類內的函式

class TestA:
    def __init__(self):
        self.config_dict = {
            "be_called_function_name": "self.be_called_function()",
        }
        pass

    def active_call_function(self):
        print("here is active_call_function.")
        be_called_function_name = self.config_dict["be_called_function_name"]
        # 就直接呼叫。如果有其他引數,一樣地傳就好了
        # 另外也可以是"be_called_function_name"是"be_called_function",然後eval(be_called_function_name)()
        eval(be_called_function_name)
        pass

    def be_called_function(self):
        print("here is be_called_function.")

if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

2 透過eval呼叫同一個檔案內的一級函式

class TestA:
    def __init__(self):
        self.config_dict = {
            "be_called_function_name": "be_called_function()",
        }
        pass

    def active_call_function(self):
        print("here is active_call_function.")
        be_called_function_name = self.config_dict["be_called_function_name"]
        # 就直接呼叫。如果有其他引數,一樣地傳就好了
        # 另外也可以是"be_called_function_name"是"be_called_function",然後eval(be_called_function_name)()
        eval(be_called_function_name)
        pass

def be_called_function():
    print("here is be_called_function.")

if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

二、透過getattr實現

1 透過函式名呼叫同一個類內的函式

class TestA:
    def __init__(self):
        self.config_dict = {
            "be_called_function_name": "be_called_function",
        }
        pass

    def active_call_function(self):
        print("here is active_call_function.")
        # getaattr(module_name, function_name),module_name傳self即可
        be_called_function = getattr(self, self.config_dict["be_called_function_name"])
        # 就直接呼叫。如果有其他引數,一樣地傳就好了
        be_called_function()
        pass

    def be_called_function(self):
        print("here is be_called_function.")


if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

2 透過函式名呼叫其他類的函式

class TestA:
    def __init__(self):
        self.config_dict = {
            "be_called_function_name": "be_called_function",
        }
        pass

    def active_call_function(self):
        print("here is active_call_function.")
        # getaattr(module_name, function_name),module_name傳被呼叫的函式所在的類的類例項
        testb_obj = TestB()
        be_called_function = getattr(testb_obj, self.config_dict["be_called_function_name"])
        # 就直接呼叫。如果有其他引數,一樣地傳就好了
        be_called_function()
        pass


class TestB:
    def be_called_function(self):
        print("here is be_called_function.")


if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

3 透過函式名呼叫同檔案的一級函式

import sys


class TestA:
    def __init__(self):
        self.config_dict = {
            "be_called_function_name": "be_called_function",
        }
        pass

    def active_call_function(self):
        print("here is active_call_function.")
        # getaattr(module_name, function_name),module_name傳當前模組名
        module_name = sys.modules['__main__']
        be_called_function = getattr(module_name, self.config_dict["be_called_function_name"])
        # 就直接呼叫。如果有其他引數,一樣地傳就好了
        be_called_function()
        pass


def be_called_function():
    print("here is be_called_function.")


if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

4 透過函式名呼叫在其他檔案的一級函式

class TestA:
    def __init__(self):
        self.config_dict = {
            "be_called_function_name": "be_called_function",
        }
        pass
        
	#學習中遇到問題沒人解答?小編建立了一個Python學習交流群:153708845
    def active_call_function(self):
        print("here is active_call_function.")
        # getaattr(module_name, function_name),module_name傳函式所在模組名
        # __import__()傳函式所在檔案
        module_name = __import__("test_call_function_by_string1")
        be_called_function = getattr(module_name, self.config_dict["be_called_function_name"])
        # 就直接呼叫。如果有其他引數,一樣地傳就好了
        be_called_function()
        pass


if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

相關文章