在包中定义类 [英] Define Classes in Packages
问题描述
我正在学习Python,并且一直在研究软件包.我想知道在包中定义类的最佳方法.似乎在包中定义类的唯一方法是在该包的__init__.py
中定义它们.来自Java,我想为类定义单个文件.这是推荐做法吗?
I'm learning Python and I have been playing around with packages. I wanted to know the best way to define classes in packages. It seems that the only way to define classes in a package is to define them in the __init__.py
of that package. Coming from Java, I'd kind of like to define individual files for my classes. Is this a recommended practice?
我想让我的目录看起来像这样:
I'd like to have my directory look somewhat like this:
recursor/
__init__.py
RecursionException.py
RecursionResult.py
Recursor.py
所以我可以将我的类称为recursor.Recursor
,recursor.RecursionException
和recursor.RecursionResult
.这是可行的还是在Python中推荐?
So I could refer to my classes as recursor.Recursor
, recursor.RecursionException
, and recursor.RecursionResult
. Is this doable or recommended in Python?
推荐答案
继续在单独的模块中定义类.然后让__init__.py
做这样的事情:
Go ahead and define your classes in separate modules. Then make __init__.py
do something like this:
from RecursionException import RecursionException
from RecursionResult import RecursionResult
from Recursor import Recursor
这会将每个类导入包的根名称空间,因此调用代码可以引用recursor.Recursor
而不是recursor.Recursor.Recursor
.
That will import each class into the package's root namespace, so calling code can refer to recursor.Recursor
instead of recursor.Recursor.Recursor
.
不过,我觉得有必要在这里回应其他一些评论:Python不是Java.我建议不要将密切相关的类分组到单个模块中,而不是为阳光下的每个类创建一个新的模块.这样一来,您的代码就更容易理解,并且调用代码不需要大量的导入.
I feel the need to echo some of the other comments here, though: Python is not Java. Rather than creating a new module for every class under the sun, I suggest grouping closely related classes into a single module. It's easier to understand your code that way, and calling code won't need a bazillion imports.
这篇关于在包中定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!