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

问题描述:

目录结构

top
main.py
└ target.py

代码

#----main.py
import target
target.fun()
'''
输出结果
C:\Users\Administrator\Desktop\top>python main.py
target-other
target-function
'''

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

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

解决方案

if __name__=='__main__':

  pass

猜你喜欢

转载自www.cnblogs.com/remly/p/11546201.html