Python中模块互相调用的例子

假设代码结构如下:

- 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

猜你喜欢

转载自www.linuxidc.com/Linux/2019-05/158423.htm