如果我在函数中导入模块,变量是局部变量吗?

2024-04-10

如果我在函数(本地范围)内导入 python 3 中的模块,导入的内容是否是该函数的本地内容?

Like

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

是的,该模块将是该函数的本地模块,至少在上面的示例中是这样(我使用的是 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果我在函数中导入模块,变量是局部变量吗? 的相关文章

随机推荐