语言-Python-main函数

在当前module里的main

  1. Python中没有不会像Java一样去找main(),会直接自上而下执行程序
#hello.py
print("first")
 
def sayHello():
    str = "hello"
    print(str);
    print(__name__+'from hello.sayhello()')
 
if __name__ == "__main__":
    print ('This is main of module "hello.py"')
    sayHello()
    print(__name__+'from hello.main')

运行结果

first This is main of module “hello.py” __main__from hello.main

可以看见先执行第一行再到if __name__ == "__main__"

if _name_ == “_main_

  1. _name__为内置属性,在当前module中,不管是那个位置__name__属性,其值都是__main_
  2. 当前的文件作为模块被导入其他文件时,__name__的值就为当前的py文件名(import hello_world.py, 那么__name__就是hello_world)
import hello#上一个例子的hello.py
 
if __name__ == "__main__":
    print ('This is main of module "world.py"')
    hello.sayHello()
    print(__name__)

运行结果

first This is main of module “world.py” hello hellofrom hello.sayhello() __main__

知乎示例

# const.py
PI = 3.14

def main():
print "PI:", PI

main()

# area.py
from const import PI

def calc_round_area(radius):
return PI * (radius ** 2)

def main():
print "round area: ", calc_round_area(2)

if __name__ == "__main__"#如果不加则会同时输出const.py中的main函数
main()	
Table of Contents