[语言基础] 我只想导入目标包中的一个模块,没想到目标包的其他非模块代码也被执行了。。

问题描述:

目录结构

top
main.py
└ target.py

代码

#----main.py
import target
target.fun()
'''
输出结果
C:UsersAdministratorDesktop	op>python main.py
target-other
target-function
'''

#----target.py
def fun():
    print('target-function')
print('target-other')

可见导入模块target,即执行import target的时候会把非模块的代码执行一遍

 参考Python学习手册P542

import会一次运行在目标文档中的语句从而建立其中的内容

解决方案

if __name__=='__main__':

  pass

原文地址:https://www.cnblogs.com/remly/p/11546201.html