英文:
Passing package name and function name as variable in python
问题
pkgName = 'f1'
fnName = 'fn1'
from pkgName import fnName
英文:
I have a function defined in file f1.py
as:
def fn1():
return 1
def fn2():
return 2
For learning exercise I am trying the following, which works:
import f1
from f1 import fn1, fn2
But the following approach doesn't work:
pkgName = 'f1'
fnName = 'fn1'
from pkgName import fnName
How can I pass package name and function name as variable?
答案1
得分: 1
你可以使用__import__
函数首先导入模块,然后通过getattr
将函数作为模块对象的属性访问:
module_name = 'f1'
function_name = 'fn1'
fn = getattr(__import__(module_name, fromlist=[function_name]), function_name)
fn()
英文:
You can use the __import__
function to import the module first, and then access the function as an attribute of the module object with getattr
:
module_name = 'f1'
function_name = 'fn1'
fn = getattr(__import__(module_name, fromlist=[function_name]), function_name)
fn()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论