【Python main 函数以及 __name__属性】

熟悉Java 或 C/C++ 程序的用户都知道,程序的执行需要入口程序。例如,在Java中,我们在准备 Run 的类中总会定义如下的main方法作为程序入口。

public static void main(String []args){
    // TODO.
}

而在Python的 ".py" 文件中,Python解释器会执行暴露在 function中之外的全局代码。对于main方法实际上只是我们逻辑的区分。典型的写法为:

# hello.py
if __name__ == "__main__":
    some_function()

从代码逻辑可以看出,程序会判断 **"__name__"** 属性的值是否为 "__main__",如果是,则执行some_function(),如果不是,则不会做任何操作。
name 以双下划线开头,表明该属性是Python的系统内置属性。该属性的取值分为两种情况:

当前模块作为主执行模块时:则 \__name__ 的值为 \__main__
当前模块不是主执行模块时:则 \__name__ 的值为当前模块的模块名

例如,在终端中直接执行 python hello.py,则此时,hello.py是执行的主模块,则 __name__ 的值为 __main__ 。如果通过import hello的形式引入hello.py模块,并调用hello模块中的方法,则 __name__的值为 "hello".

更多内容请关注微信公众号:
SystemEngineeringLab

猜你喜欢

转载自www.cnblogs.com/nelson2013/p/9251952.html