简体   繁体   English

如果我在函数内导入模块,变量是否为局部变量?

[英]If I import a module inside a function, will the variables be local?

If I do an import of a module in python 3 inside a function (local scope), will the things imported be local to the function? 如果我在函数(本地范围)内的python 3中进行模块的导入,导入的内容对函数而言是本地的吗?

Like 喜欢

def test():
    import math
    s = math.cos(1)
s = math.cos(1)

Yes, the module will be local to the function, at least in the example above(I am using Python 3.6). 是的,至少在上面的示例中(我使用的是Python 3.6),该模块对于该函数而言是局部的。

Example: 例:

Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
def test():
...     import math
...     s = math.cos(1)
...
g = math.cos(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined

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

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