如何安装 Python 配方文件 (.py)?

发布于 2024-09-24 20:46:31 字数 590 浏览 7 评论 0原文

我是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巴黎夜雨 2024-10-01 20:46:31

有两个密切相关的问题。

首先,在recipes.py中,您需要访问所有itertools。

至少,这意味着你需要

import itertools

处于顶层。但在这种情况下,您需要将所有 itertools 函数限定为 itertools.,如您所说。 (您也可以使用import itertools as it,然后使用it.。)

其次,您可以这样做

from itertools import islice, count, chain

,但需要将所有需要的函数放入名单。

最后,最不推荐但可能最简单的做法是这样做,

from itertools import *

这很危险,因为它会用来自 itertools一切污染你的命名空间,这被认为是不好的且不受控制的,但在这种情况下案件或许并不可怕。

第二,您在使用 recipes.py 的所有代码中都存在类似的问题;您需要限定或显式导入所有内容。所以,

import recipes
recipes.take(...)

要么

from recipes import take
take(...)

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

import itertools

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 use import itertools as it and then it.<funcname>.)

Second, you could do

from itertools import islice, count, chain

but you would need to put all of the needed functions in the list.

Finally, the least recommended, but probably easiest, is to do

from itertools import *

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, either

import recipes
recipes.take(...)

or

from recipes import take
take(...)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文