时间:2023-01-31 13:28:01 | 来源:建站知识
时间:2023-01-31 13:28:01 来源:建站知识
作者:leetaoif __name__ == '__main__': func_name()那么这一行代码有什么具体的作用呢,不加的话会对我们的结果造成影响吗?__name____name__,我们常见的还有 __init__,__dict__ 等等.那么有多少内置变量呢?我们可以通过下面在交互界面输入下面的命令,查看 Python 全部内置变量和内置函数>>> dir(__builtins__)结果如下图:__name__ 的值__name__ 在不同情况下会有不同值,它的值取决于我们是如何执行脚本的.我们可以通过几个例子感受一下:# test.pyprint(f'__name__ 在 test.py 值为 {__name__}')然后直接执行一下代码$ python test.py然后看一下输出$ python test.py __name__ 在 test.py 值为 __main__在这个例子中,我们发现 __name__ 的值是 __main__# test1.pyimport testprint(f'__name__ 在 test1.py 值为 {__name__}')接着执行一下 test1.py,再看一下输出python test1.py __name__ 在 test.py 值为 test__name__ 在 test1.py 值为 __main__结果是不是很有意思?整个过程是什么样子的呢?简单的画了一个图__name____name__ 了. 这里通过改造上面 Example 1的例子来直观感受一下# test.pydef hello(name): print(f'Hello,{name}') if __name__ == '__main__': hello("test")再修改一下 test1.py 文件# test1.pyfrom test import hellohello("test1")然后让我们先尝试直接运行一下 test.py,很显然这个时候, if 语句条件满足,会输出 Hello,test$ python test.py Hello,test这个时候我们如果运行 test1.py,程序就会输出 Hello,test1 了$ python test1.py Hello,test1如果我们把 if __name__ == "__main__" 在 test.py 去掉会发生什么呢?$ python test1.py Hello,testHello,test1__name__, and then__name__ checks we always see in Python scripts.foo.py.# Suppose this is foo.py.print("before import")import mathprint("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")__name__ variable.python foo.pythe interpreter will assign the hard-coded string "__main__" to the __name__ variable, i.e.# It's as if the interpreter inserts this at the top# of your module when run as the main program.__name__ = "__main__"When Your Module Is Imported By Another# Suppose this is in some other main program.import fooThe interpreter will search for your foo.py file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo" from the import statement to the __name__ variable, i.e.# It's as if the interpreter inserts this at the top# of your module when it's imported from another module.__name__ = "foo"关键词: