这篇文章主要是对py文件里的__name__=='__main__'
的其中一个用法的演示。
'''
test.py
'''
print(100)
def a():
print(200)
if __name__ == '__main__':
print(300)
a()
def b():
print(400)
C:\Users\888\Desktop>python test.py
100
300
200
>>> import test
100
>>> test.a()
200
>>> test.b()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'test' has no attribute 'b'
if __name__ == '__main__'
之下的代码块将被运行;当.py文件以模块形式被导入时,if __name__ == '__main__'
之下的代码块不被运行。if __name__ == '__main__'
之下写函数是没有用的,无法调用,函数应该写在__name__
之上,同理,本py文件里import其他模块的时候也是。Python — Jul 31, 2022
Made with ❤ and at Earth.