将包名和函数名作为变量传递给Python

huangapple go评论72阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2020年1月4日 01:21:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582748.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定