在Python中,是“来自Module import ClassName”的成语“典型? [英] In Python, is the idiom "from Module import ClassName" typical?
问题描述
由于我更喜欢小文件,我通常会为每个Python模块放置一个公共类。我将模块命名为与其包含的类相同的名称。例如,类 ToolSet
将在 ToolSet.py
中定义。
Since I prefer small files, I typically place a single "public" class per Python module. I name the module with the same name as the class it contains. So for example, the class ToolSet
would be defined in ToolSet.py
.
在一个包中,如果另一个模块需要实现类ToolSet的对象,我使用:
Within a package, if another module needs to instanciate an object of class ToolSet, I use:
from ToolSet import ToolSet
...
toolSet = ToolSet()
而不是:
import ToolSet
...
toolSet = ToolSet.ToolSet()
我这样做是为了减少口吃(我更喜欢在文件顶部比在我的代码中口吃。)
I do this to reduce "stutter" (I prefer to have stutter at the top of the file than within my code.)
这是一个正确的习语吗?
Is this a correct idiom?
这是一个相关的问题。在一个软件包中,我经常会有一些我希望向外界展示的课程。这些我导入该包的 __ init __。py
。例如,如果 ToolSet
在包 UI
中,我想公开它,我会在<$中添加以下内容c $ c> UI / __ init __。py :
Here is a related question. Within a package, I often have a small number of classes that I would like to expose to the outside world. These I import inside the __init__.py
for that package. For example, if ToolSet
is in package UI
and I want to expose it, I would put the following in UI/__init__.py
:
from ToolSet import ToolSet
因此,从外部模块我可以写
So that, from an external module I can write
import UI
...
toolSet = UI.ToolSet()
再次,这是pythonic吗?
Again, is this pythonic?
推荐答案
回答你的第一个问题,这就是我用的习语, PEP8蟒蛇风格指南支持其使用
To answer your first question, that is the idiom I use, and its use is supported by PEP8 the python style guide
可以这样说:
it's okay to say this though:
来自子流程导入Popen,PIPE
from subprocess import Popen, PIPE
我喜欢它,因为它减少了输入并确保文件运行时出现问题(比如拼写错误的导入)而不是一段时间后,当一个函数使用g导入运行。
I like it as it reduces typing and makes sure that things go wrong immediately the file is run (say you mis-spelt an import) rather than some time later when a function using the import is run.
例如假设模块 Thing
没有 Thyng
会员
from Thing import Thyng
运行 .py
文件后立即出错,而
Goes wrong immediately you run the .py
file, whereas
import Thing
# ...
def fn():
Thing.Thyng()
在运行 fn()
关于你的第二个问题,我认为这也是一个好习惯。当我将一个large.py分解为一个带有 __ init __。py
和实现文件的目录时,我经常会遇到这种情况。将内容导入 __ init __。py
可使界面保持不变。这也是标准库中的常见做法。
As for your second question, I think that is also good practice. It often happens to me when I factor a single large.py into a directory with an __init__.py
and implementation files. Importing things into the __init__.py
keeps the interface the same. It is common practice in the standard libraries too.
这篇关于在Python中,是“来自Module import ClassName”的成语“典型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!