开发者

What does this Python code mean?

__author__="Sergio.Tapia"
__date__ ="$18-10开发者_C百科-2010 12:03:29 PM$"

if __name__ == "__main__":
    print("Hello")
    print(__author__)

Where does it get __main__ and __name__?

Thanks for the help


The __name__ variable is made available by the runtime. It's the name of the current module, the name under which it was imported. "__main__" is a string. It's not special, it's just a string. It also happens to be the name of the main script when it is executed.

The if __name__ == "__main__": mechanism is the common way of doing something when a .py file is executed directly, but not when it is imported as a module.


Python modules can also be run as standalone scripts. As such, code within the if __name__ == "__main__": block will only run if the module is executed as the "main" file.

Example:

#foo.py
def msg():
    print("bar")

if __name__ == "__main__":
    msg()

Running this module will output

$ python foo.py
bar

where as importing it will output nothing.

>>> import foo
>>> foo.msg()
bar

Reference

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜