Python:在包中定义类 [英] Python: Define Classes in Packages

查看:110
本文介绍了Python:在包中定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习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 __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。我不建议在太阳下为每个类创建一个新模块,我建议将紧密相关的类分组到一个模块中。这样更容易理解你的代码,调用代码不需要bazillion导入。

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.

这篇关于Python:在包中定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆