能否在当前Python文件中导入自定义模块的嵌套函数test2()?
能否直接导入嵌套函数test2()?
不能直接从Custom_module.py中导入嵌套在test1()里的test2()。
原因很直接:嵌套函数属于外层函数的局部作用域,只有当test1()被调用执行时,test2()才会被定义出来,而且外部代码无法直接访问test1内部的这个函数名称——它对外是完全不可见的。
如果想在当前文件中使用test2(),可以试试这几种可行的方法:
方法1:调整函数结构,把test2移到全局作用域
修改Custom_module.py,将test2从test1内部挪到模块的全局范围:
# Custom_module.py def test2(): print("This is test2 function") def test1(): def test3(): print("This is test3 function") # rest of the test1 func code...
之后就能直接导入使用:
from Custom_module import test2 test2() # 正常执行输出
方法2:让test1返回test2对象
修改test1,在函数末尾返回内部的test2:
# Custom_module.py def test1(): def test2(): print("This is test2 function") def test3(): print("This is test3 function") # rest of the test1 func code... return test2
在当前文件中调用test1()获取test2:
from Custom_module import test1 test2 = test1() test2() # 执行test2
方法3:添加专门的导出函数
如果不想修改test1的原有逻辑,可以在模块里加一个辅助函数来获取test2:
# Custom_module.py def test1(): def test2(): print("This is test2 function") def test3(): print("This is test3 function") # rest of the test1 func code... return test2 def get_test2(): # 调用test1并返回内部的test2 return test1()
当前文件中导入并使用:
from Custom_module import get_test2 test2 = get_test2() test2()
内容的提问来源于stack exchange,提问作者G_G
相关产品推荐
相关产品推荐

