是否建议在单个文件中使用多个类? [英] Are multiple classes in a single file recommended?
问题描述
可能重复:
我应在一个文件中放入多少个Python类?
来自C ++背景,我已经习惯于组织类,因此在大多数情况下,类与文件之间的比例为1:1。通过使其包含单个类的单个文件,我发现代码更易于导航。当我向自己介绍Python时,我发现许多示例,其中一个文件包含多个类。这是推荐的Python处理方式吗?如果是这样,为什么?
Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio between classes and files. By making it so that a single file contains a single class I find the code more navigable. As I introduce myself to Python I'm finding lots of examples where a single file contains multiple classes. Is that the recommended way of doing things in Python? If so, why?
我在 PEP8 ?
推荐答案
以下是一些可能的原因:
Here are some possible reasons:
- Python并非专门基于类-Python中代码分解的自然单位是模块。模块包含的功能(在Python中是一类对象)与类一样可能。在Java中,分解的单位是类。因此,Python具有一个module = 1个文件,而Java具有一个(公共)class = 1个文件。
- Python比Java具有更高的表现力,并且如果您将自己限制为每个类一个文件(Python不会阻止您执行该文件),最终您会得到很多非常小的文件-更多的跟踪信息几乎没有好处。
大致等效的功能示例:Java的log4j =>十几个文件,约8000个SLOC。 Python日志记录=> 3个文件,〜2800个SLOC。
An example of roughly equivalent functionality: Java's log4j => a couple of dozen files, ~8000 SLOC. Python logging => 3 files, ~ 2800 SLOC.
这篇关于是否建议在单个文件中使用多个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!