python精要(79)-模块与包组织(2)-相对导入

使用以下格式导入同级目录(包)下的模块
from .模块名(注意此处不是包名) import 模块下定义的类名或函数名等等

(base) [myhaspl@localhost learn2]$ cat m1/test11.py
from .test1 import test1
def test11():
    test1()
    print("m1.test11")
(base) [myhaspl@localhost learn2]$ 
>>> import m1
>>> m1.test11.test11()
m1.test1
m1.test11
>>> 

加入对__name__的支持,检测直接运行还是调用
https://blog.csdn.net/AI_LX/article/details/113044644


(base) [myhaspl@localhost learn2]$ python m1/test11.py
m1.test1
m1.test11

>>> import m1
>>> m1.test1.test1()
m1.test1
>>> m1.test11.test11()
m1.test11
>>> quit()
(base) [myhaspl@localhost learn2]$ cat m1/test1.py
def test1():
    print("m1.test1")
(base) [myhaspl@localhost learn2]$ cat m1/test11.py
def test11():
    print("m1.test11")
def main():
    from test1 import test1
    test1()
    test11()
if __name__=="__main__":
    main()
(base) [myhaspl@localhost learn2]$ python m1/test11.py
m1.test1
m1.test11
(base) [myhaspl@localhost learn2]$ 
相关推荐
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页