zoukankan      html  css  js  c++  java
  • [笔记]Python中模块互相调用的例子

    python中模块互相调用容易出错,经常是在本地路径下工作正常,切换到其他路径来调用,就各种模块找不到了。
    解决方法是通过__file__定位当前文件的真实路径,再通过sys.path.append()来获取相对路径更新$PATH即可。

    假设代码结构如下:

    - mod_a
        __init__.py     # 模块文件夹内必须有此文件
        aaa.py
    - mod_b
        __init__.py     # 模块文件夹内必须有此文件
        bbb.py
    - ccc.py
    
    • 调用同级模块

    如果aaa.py要调用bbb.py的内容,可以在aaa.py中如下写:

    import sys
    sys.path.append(osp.join(osp.dirname(__file__), '..'))  # 扫除路径迷思的关键!
    from mod_b.bbb import *
    
    • 调用下级模块

    如果ccc.py要调用bbb.py的内容,可以在ccc.py中如下写:

    from mod_b.bbb import *
    
    • 调用上级模块

    如果aaa.py要调用ccc.py的内容,可以在aaa.py中如下写:

    import sys
    sys.path.append(osp.join(osp.dirname(__file__), '..'))
    from ccc import *
    

    代码示例:

    aaa.py如下:

    # -*- coding: utf-8 -*-
    
    from __future__ import print_function
    import os.path as osp
    import sys
    sys.path.append(osp.join(osp.dirname(__file__), '..'))
    from mod_b.bbb import *
    from ccc import *
    
    def print_a():
      print('this is a')
      
    def _call_mod_b():
      print_a()
      print_b()
      
    def _call_mod_c():
      print_c()
    
    
    if __name__=='__main__':
      _call_mod_b()
      _call_mod_c()
    

    bbb.py如下:

    # -*- coding: utf-8 -*-
    
    from __future__ import print_function
    
    def print_b():
      print('this is b')
    
    
    if __name__=='__main__':
      pass
    

    ccc.py如下:

    # -*- coding: utf-8 -*-
    
    from __future__ import print_function
    from mod_b.bbb import *
    
    def print_c():
      print('this is c')
      
    def _call_mod_b():
      print_c()
      print_b()
      
    
    if __name__=='__main__':
      _call_mod_b()
    

    如此,当不管在何处调用aaa.py时,结果都一样,如下:

    this is a
    this is b
    this is c
    

    如果调用ccc.py,结果如下:

    this is c
    this is b
    
  • 相关阅读:
    PointToPointNetDevice doesn't support TapBridgeHelper
    NS3系列—10———NS3 NodeContainer
    NS3系列—9———NS3 IP首部校验和
    NS3系列—8———NS3编译运行
    【习题 7-6 UVA
    【Good Bye 2017 C】 New Year and Curling
    【Good Bye 2017 B】 New Year and Buggy Bot
    【Good Bye 2017 A】New Year and Counting Cards
    【Educational Codeforces Round 35 D】Inversion Counting
    【Educational Codeforces Round 35 C】Two Cakes
  • 原文地址:https://www.cnblogs.com/journeyonmyway/p/9492544.html
Copyright © 2011-2022 走看看