Organizing Python classes in modules and/or packag

2019-01-30 07:50发布

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

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

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?

2条回答
疯言疯语
2楼-- · 2019-01-30 08:04

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

and then in your __init__.py file:

from baseconverter import BaseConverter
from otherconverter import OtherConverter
查看更多
▲ chillily
3楼-- · 2019-01-30 08:13

Zach's solution breaks on Python 3. Here is a fixed solution.

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

and then in your __init__.py file:

from converters.baseconverter import BaseConverter
from converters.otherconverter import OtherConverter
查看更多
登录 后发表回答