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

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

问题描述

我喜欢Java惯例,每个文件有一个公共类,即使有时有很好的理由把多个公共类放入一个文件。在我的情况下,我有相同的接口的替代实现。但如果我将它们放在单独的文件中,我会在import语句(或误导的模块名称)中有多余的名称:

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 类名。这看起来对我来说很不高兴。将所有的替代类放在一个文件中将导致更有意义的import语句:

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 (或从转换器导入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 文件中:

from baseconverter import BaseConverter
from otherconverter import OtherConverter

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

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