python中通过字符串调用同名函数

xiaoxiao2021-02-28  98

本文记录在python中如何根据字符串调用以该字符串命名的函数的方法。

主要可以通过以下两种方式调用

使用getattr方法 使用__dict__字典

上代码

import sys method = 'get_sum' def get_sum(a, b): return a + b if __name__ == '__main__': #方法一:通过getattr mod = sys.modules["__main__"] sum = getattr(mod, method) print sum(4, 3) #方法二:通过__dict__字典 print mod.__dict__[method](2, 6)
转载请注明原文地址: https://www.6miu.com/read-54799.html

最新回复(0)