如果我在一个函数中导入一个模块,变量会是局部的吗? [英] If I import a module inside a function, will the variables be local?

查看:22
本文介绍了如果我在一个函数中导入一个模块,变量会是局部的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在一个函数(局部作用域)内导入了Python3中的一个模块,那么导入的内容会是该函数的本地对象吗?

喜欢

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

推荐答案

是,模块将是函数的本地模块,至少在上面的示例中是这样(我使用的是Python3.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

这篇关于如果我在一个函数中导入一个模块,变量会是局部的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆