
说明
1、当Python解释器读取源文件时,它首先定义一些特殊的变量。
2、设置一些特殊的变量,如__name__,然后执行文件中找到的所有代码。
Python解释器使用代码为__name__变量值,即__name__变量值为__main__。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # Suppose this is foo.py.
print( "before import" )
import math
print( "before functionA" )
def functionA():
print( "Function A" )
print( "before functionB" )
def functionB():
print( "Function B {}" .format(math.sqrt(100)))
print( "before __name__ guard" )
if __name__ == '__main__' :
functionA()
functionB()
print( "after __name__ guard" )
|
以上就是Python解释器读取源文件的方法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。