[英]Unexpected behavior with loading a module in Python
As far as I understood, from module import *
means that everything from the module will be locally available. 据我了解,
from module import *
表示from module import *
中的所有内容都将在本地可用。
In my code I found: 在我的代码中,我发现:
from tkinter import *
and 和
from tkinter import filedialog
Looking back, I figured I could drop this last line, but then it is unavailable: 回顾过去,我认为可以删除最后一行,但是它不可用:
NameError: name 'filedialog' is not defined.
What am I missing? 我想念什么?
From what I understand, Tkinter is a package (which means that it contains other modules). 据我了解,Tkinter是一个程序包(这意味着它包含其他模块)。 From Tkinter import * will only give you the default modules.
从Tkinter导入*仅会为您提供默认模块。
from the documentation: 从文档中:
6.4.1. 6.4.1。 Importing * From a Package
从包导入*
Now what happens when the user writes from sound.effects import *?
现在,当用户从sound.effects import *书写时会发生什么? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all.
理想情况下,希望这种方式能够进入文件系统,找到包中存在哪些子模块,然后将其全部导入。 This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.
这可能会花费很长时间,并且导入子模块可能会产生有害的副作用,这些副作用只有在明确导入子模块时才会发生。
The only solution is for the package author to provide an explicit index of the package.
唯一的解决方案是让程序包作者提供程序包的显式索引。 The import statement uses the following convention: if a package's init .py code defines a list named all , it is taken to be the list of module names that should be imported when from package import * is encountered.
import语句使用以下约定:如果包的init .py代码定义了一个名为all的列表,则将其视为遇到从包import *时应导入的模块名称的列表。 It is up to the package author to keep this list up-to-date when a new version of the package is released.
发行新版本的软件包时,软件包作者有责任使此列表保持最新。 Package authors may also decide not to support it, if they don't see a use for importing * from their package.
如果软件包作者没有看到从软件包中导入*的用途,他们可能还会决定不支持它。 For example, the file sounds/effects/ init .py could contain the following code:
例如,文件sounds / effects / init .py可能包含以下代码:
Please, read the following post for another answer to your question. 请阅读以下帖子,以获取对您问题的另一种答案。 filedialog, tkinter and opening files
文件对话框,tkinter和打开文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.