if _name_ == ‘_main_’ 我们简单的理解就是: 如果模块是被直接运行的,则代码块被运行,如果模块是被导入的,则代码块不被运行。
直接上例子:
现在有两个文件,一个为const.py ,一个为area.py。
const.py代码:
PI = 3.14
def main():
print "PI:", PI
main()
运行结果为:
>> PI:3.14
area.py代码:
from const import PI
def calc_round_area(radius):
return PI * (radius ** 2)
def main():
print "round area: ", calc_round_area(2)
main()
运行结果为:
>> PI: 3.14
>> round area: 12.56
我们想要的area.py的运行结果是输出 “round area:12.56”,但是在运行过程中因为导入了const.py中的 “PI” ,所以又执行了一遍const.py中的程序。
在const.py 代码末尾添加 if _name_ == ‘_main_’ :
PI = 3.14
def main():
print "PI:", PI
if __name__ == "__main__":
main()
再次执行 area.py 输出结果为:
>> round area: 12.56
参考文献: