Python中导入的模块/功能的范围 [英] Scope of imported modules/functions in Python

查看:62
本文介绍了Python中导入的模块/功能的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是这里的新手,不是100%知道如何问这个问题,所以我将继续深入.我应该在每个函数的开头使用import语句,我编写的函数会导入所有各个模块/我需要该功能范围的功能?即

I'm new here and am not 100% sure how to ask this question so I'll just dive right in. Should I be using import statements at the beginning of every function I write that import all of the various modules/functions I need for that function's scope? i.e.

def func1()
    import os.path
    print func(2)
    do something with os.path

def func2()
    import os.path
    do something with os.path

这会增加内存开销或其他开销,还是import语句只是将本地名称映射到已加载的对象?有更好的方法吗? (非常欢迎转到教程等的链接.我已经找了一段时间,但找不到很好的答案.)

Will this increase memory overheads, or other overheads, or is the import statement just mapping a local name to an already loaded object? Is there are better way to do this? (Links to tutorials etc. most welcome. I've been looking for a while but can't find a good answer to this.)

推荐答案

该模块仅在首次导入时才被处理;随后的导入将仅复制对本地范围的引用.但是,最好是在可能的情况下将其导入模块顶部的样式.有关详细信息,请参见PEP 8.

The module will only be processed the first time it is imported; subsequent imports will only copy a reference to the local scope. It is however best style to import at the top of a module when possible; see PEP 8 for details.

这篇关于Python中导入的模块/功能的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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