从导入,同时保留按模块的访问 [英] From-Import while retaining access by module

查看:96
本文介绍了从导入,同时保留按模块的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题有点难以理解,但是我的问题很简单。

The title is a little hard to understand, but my question is simple.

我有一个程序需要使用 sqrt( ),但这是我从数学中唯一需要的东西。导入整个模块以获取单个功能似乎有点浪费。

I have a program that needs to take the sqrt() of something, but that's the only thing I need from math. It seems a bit wasteful to import the entire module to grab a single function.

我可以说来自数学导入sqrt的 ,但随后是 sqrt()将被添加到程序的主命名空间中,而我不希望这样做(尤其是因为我计划将程序更改为可用作模块;在这种情况下那样导入会导致问题吗?)。有什么方法可以只导入一个函数,同时仍然保留 math.sqrt()语法?

I could say from math import sqrt, but then sqrt() would be added to my program's main namespace and I don't want that (especially since I plan to alter the program to be usable as a module; would importing like that cause problems in that situation?). Is there any way to import only that one function while still retaining the math.sqrt() syntax?

I在这种特定情况下,我正在使用Python 2.7,但是如果对Python 3有不同的答案,我也想听听一下,以备将来参考。

I'm using Python 2.7 in this specific case, but if there's a different answer for Python 3 I'd like to hear that too for future reference.

推荐答案

无论哪种方式,您都可以导入完整的 math 模块,因为它已编译并存储在 sys.modules 。因此,与导入数学相比,使用数学导入sqrt 进行操作不会带来任何优化优势。他们做的完全一样。他们导入整个数学模块,将其存储为 sys.modules ,然后唯一的区别是第一个带来了 sqrt 函数进入名称空间,第二个函数将 math 模块引入您的命名空间。但是名称只是引用,因此仅从模块中导入一件事就不会对内存或CPU有所帮助。

Either way you "import" the complete math module in a sense that it's compiled and stored in sys.modules. So you don't have any optimisation benefits if you do from math import sqrt compared to import math. They do exactly the same thing. They import the whole math module, store it sys.modules and then the only difference is that the first one brings the sqrt function into your namespace and the second one brings the math module into your namespace. But the names are just references so you wont benefit memory wise or CPU wise by just importing one thing from the module.

如果您想使用 math .sqrt 语法,然后只需使用导入数学。如果要使用 sqrt()语法,请使用 from math import sqrt

If you want the math.sqrt syntax then just use import math. If you want the sqrt() syntax then use from math import sqrt.

如果您关注的是保护您的模块用户免于污染其命名空间,如果他执行星号导入: from your_module import * 然后定义一个 __ all __ 变量,该变量是表示对象的字符串的列表,如果您的模块的用户开始导入,则将导入这些对象。

If your concern is protecting the user of your module from polluting his namespace if he does a star import: from your_module import * then define a __all__ variable in your module which is a list of strings representing objects that will be imported if the user of your module does a start import.

这篇关于从导入,同时保留按模块的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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