繁体   English   中英

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

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

如果我在函数(本地范围)内的python 3中进行模块的导入,导入的内容对函数而言是本地的吗?

喜欢

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

是的,至少在上面的示例中(我使用的是Python 3.6),该模块对于该函数而言是局部的。

例:

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