如何安装 Python 配方文件 (.py)?
我是Python新手。我目前正在使用 Py3k (Win)。
我在安装 .py
文件时遇到问题。基本上,我想使用此页面底部提供的食谱。因此,我想将它们放入 .py
中,并在任何源代码中导入
它们。
因此,我将所有食谱复制到recipes.py 文件中,并将它们复制到C:\Python3k\Lib\site-packages。
现在,导入工作正常,但是当我尝试从中调用任何函数(例如 take
)时,我得到一个全局名称“islice”不是定义...所以我想,我应该将 itertools
导入添加到 recipes.py
我仍然遇到相同的错误?我需要将所有实例更改为 itertools.
吗?我怎样才能使进口成为全球性的?这是 Py3k 的新变化吗?我有什么遗漏的吗?
提前致谢, :)
I'm new to Python. I'm currently on Py3k (Win).
I'm having trouble installing a .py
file. Basically, i want to use the recipes provided at the bottom of this page. So i want to put them inside a .py
and import
them in any of my source codes.
So i copied all the recipes into a recipes.py
file and copied them to C:\Python3k\Lib\site-packages
.
Now, the import
works fine, but when i try to call any function (eg. take
) from it, i got a global name 'islice' is not defined
...So i figured, i should add an itertools
import to recipes.py
I still get the same error? Do i need to change all instances to itertools.<funcname>
? how can i make the import's global? Is this a new Py3k change? Is there something i missing?
Thanks in advance, :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两个密切相关的问题。
首先,在recipes.py中,您需要访问所有itertools。
至少,这意味着你需要
处于顶层。但在这种情况下,您需要将所有 itertools 函数限定为
itertools.
,如您所说。 (您也可以使用import itertools as it
,然后使用it.
。)其次,您可以这样做
,但需要将所有需要的函数放入名单。
最后,最不推荐但可能最简单的做法是这样做,
这很危险,因为它会用来自
itertools
的一切污染你的命名空间,这被认为是不好的且不受控制的,但在这种情况下案件或许并不可怕。第二,您在使用
recipes.py
的所有代码中都存在类似的问题;您需要限定或显式导入所有内容。所以,要么
There are two closely-related issues.
First, within recipes.py, you need access to all of itertools.
At the very least, this means you need
at the top. But in this case you would need to qualify all of the itertools functions as
itertools.<funcname>
, as you say. (You could also useimport itertools as it
and thenit.<funcname>
.)Second, you could do
but you would need to put all of the needed functions in the list.
Finally, the least recommended, but probably easiest, is to do
This is dangerous because it pollutes your namespace with everything from
itertools
, which is considered bad and uncontrolled, but in this case probably isn't terrible.Second, you have a similar problem in all of your code that uses
recipes.py
; you'll need to qualify or explicitly import everything. So, eitheror