python3.x - python3 from .a import b 使用 __import__() 函数如何写?
天蓬老师
天蓬老师 2017-04-17 14:38:43
[Python讨论组]

如题所写 python3 中 from .a import b 语句如何使用 __import__() 内置函数写呢?

已知下面这两个path的导入结果是一致的:

from os import path
path = getattr(__import__("os"), "path")

那目前有这样的目录结构:

run.py
app/__init__.py
app/index.py
app/ins.py

run.py:
from app import root
root()

app/__init__.py:
from .ins import ins
from .index import root

app/index.py:
from . import ins
def root():
    print(ins)

app/ins.py
ins = "test func"

__init__.py 中使用 from .index import root 是可以正常导入的,那如何将这个 from import 语句替换为 使用 __import__() 函数来写呢?(from 的时候 是从 .index 里面导入的,请不要忘记这个点)

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(1)
迷茫

类似这样吗?

app/__init__.py:
path = getattr(__import__("sys"), "path")
path.append("app")

root = getattr(__import__("index"), "root")
ins = getattr(__import__("ins"), "ins")

app/index.py:
ins = getattr(__import__("ins"), "ins")

def root():
    print(ins)

path.append("app") 还得改成绝对路径。不知道为什么不直接使用import。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号