在模块和/或包中组织 Python 类 [英] Organizing Python classes in modules and/or packages

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

问题描述

我喜欢每个文件有一个公共类的 Java 约定,即使有时有充分的理由将多个公共类放入单个文件中.就我而言,我有相同接口的替代实现.但是,如果我将它们放入单独的文件中,我会在导入语句(或误导性的模块名称)中有多余的名称:

I like the Java convention of having one public class per file, even if there are sometimes good reasons to put more than one public class into a single file. In my case I have alternative implementations of the same interface. But if I would place them into separate files, I'd have redundant names in the import statements (or misleading module names):

import someConverter.SomeConverter

someConverter 将是文件(和模块)名称,而 SomeConverter 将是类名称.这对我来说看起来很不优雅.将所有替代类放在一个文件中会导致更有意义的导入语句:

whereas someConverter would be the file (and module) name and SomeConverter the class name. This looks pretty inelegant to me. To put all alternative classes into one file would lead to a more meaningful import statement:

import converters.SomeConverter

但是我担心如果我将所有相关的类放在一个模块文件中,文件会变得非常大.这里的 Python 最佳实践是什么?每个文件一个班级不寻常吗?

But I fear that the files become pretty large, if I put all related classes into a single module file. What is the Python best practise here? Is one class per file unusual?

推荐答案

很多都是个人喜好.使用 python 模块,你可以选择将每个类保存在一个单独的文件中,并且仍然允许 import converters.SomeConverter(或 from converters import SomeConverter)

A lot of it is personal preference. Using python modules, you do have the option to keep each class in a separate file and still allow for import converters.SomeConverter (or from converters import SomeConverter)

您的文件结构可能如下所示:

Your file structure could look something like this:

* converters
     - __init__.py
     - baseconverter.py
     - someconverter.py
     - otherconverter.py

然后在您的 __init__.py 文件中:

and then in your __init__.py file:

from baseconverter import BaseConverter
from otherconverter import OtherConverter

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

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