简体   繁体   English

究竟导入将在python中做什么

[英]What exactly import will do in python

I have written a python file a.py like this: 我写了一个像这样的python文件a.py

x = 1
def hello():
   print x

hello()

When I do import a , it is printing the value of x 当我import a ,它会打印x的值

Till now my understanding is import will include the variables and function definitions but why it is executing the method hello() ? 直到现在我的理解是import将包括变量和函数定义,但为什么它执行方法hello()

Python imports are not trivial, but in short, when a module gets imported, it is executed top to bottom . Python导入并不简单,但简而言之,当导入模块时,它会从上到下执行。 Since there is a call to hello, it will call the function and print hello. 由于调用了hello,它将调用该函数并打印hello。

For a deeper dive into imports, see: 要深入了解进口,请参阅:

To be able to use a file both standalone and as a module, you can check for __name__ , which is set to __main__ , when the program runs standalone: 为了能够独立使用文件和作为__main__ ,当程序独立运行时,您可以检查__name__ ,它被设置为__main__

if __name__ == '__main__':
    hello()

See also: What does if __name__ == "__main__": do? 另请参见: 如果__name__ ==“__ main__”,该怎么办?

In Python, there is no clear separation between declaring and executing. 在Python中,声明和执行之间没有明确的区别。 In fact, there are only execution statements. 实际上,只有执行语句。 For example, def hello():... is just a way to assign a function value to the module variable hello . 例如, def hello():...只是一种将函数值赋给模块变量hello All the statements in the module are executed in their order once the module is imported. 导入模块后,模块中的所有语句都按其顺序执行。

That's why they often use guards like: 这就是为什么他们经常使用像这样的守卫:

if __name__=='__main__':
   # call hello() only when the module is run as "python module.py"
   hello()

你在底部调用了hello()函数,所以当你执行“import a”时它将执行该函数!

you need to remove the hello() at the end, that is what is executing the function. 你需要删除最后的hello() ,这就是执行该函数的内容。 You only want the declarations in your file a.py 您只需要文件中的声明a.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM