V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
911061873
V2EX  ›  Python

Python 重复导入的问题

  •  
  •   911061873 · 2021-09-17 13:42:17 +08:00 · 1807 次点击
    这是一个创建于 944 天前的主题,其中的信息可能已经有所发展或是发生改变。

    项目目录如下

    │ a.py
    └─api
    	b.py
    	__init__.py
    

    a 中的内容

    from api.b import test
    aaa = 'a'
    test()
    

    b 中的内容

    from a import aaa
    def test():
        print(aaa)
    

    现在执行 a 就提示导入重复。不知道怎么解决

    11 条回复    2021-09-22 09:47:55 +08:00
    yunyuyuan
        1
    yunyuyuan  
       2021-09-17 13:47:25 +08:00
    a 改成
    ```python
    aaa = 'a'
    from api.b import test
    test()
    ```
    911061873
        2
    911061873  
    OP
       2021-09-17 13:49:55 +08:00
    @yunyuyuan 如果只是换了下位置 我试了下好像还是不行
    zhuangzhuang1988
        3
    zhuangzhuang1988  
       2021-09-17 13:54:42 +08:00
    看下 <effective python>
    第 88 条 用适当的方式打破循环依赖关系 // 350
    https://book.douban.com/subject/35334595/
    LicenseXu
        4
    LicenseXu  
       2021-09-17 13:55:18 +08:00
    b.py 里的 import 放到函数 test 里面
    def test():
    from a import aaa
    print(aaa)
    yunyuyuan
        5
    yunyuyuan  
       2021-09-17 15:12:51 +08:00
    @911061873 搞忘了,要加 main 的,这样就行了。

    aaa = 'aaa'

    if __name__ == '__main__':
    from api.b import test
    test()
    yunyuyuan
        6
    yunyuyuan  
       2021-09-17 15:13:11 +08:00
    v 站到底怎么发代码
    2owe
        7
    2owe  
       2021-09-17 15:24:03 +08:00
    增加 c,将 aaa 移到 c 中,让 c 可以被其它引用
    Nich0la5
        8
    Nich0la5  
       2021-09-17 16:17:24 +08:00
    这不是循环依赖吗 不要这么搞
    jaredyam
        9
    jaredyam  
       2021-09-17 23:47:11 +08:00
    竟然还能从 b 里导入 a,就很神奇
    jaredyam
        10
    jaredyam  
       2021-09-17 23:49:40 +08:00
    你这种写法还会出很多其它问题,里包导外包应该使用相对导入,from ..a import ...
    frostming
        11
    frostming  
       2021-09-22 09:47:55 +08:00
    def test():
    from a import aaa
    print(aaa)

    把 import 移到 test 里面去就解决问题了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2916 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:30 · PVG 08:30 · LAX 17:30 · JFK 20:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.