Possible Duplicate:
How many Python classes should I put in one file?
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?
Am I missing this convention in the PEP8?
In Java for instance, you cannot create multiple top level classes per file, they have to be in separate files where the classname and filename are the same.
In Python there is rule of one module=one file. In Python if you restrict yourself to one class per file (which in Python is not prohibited) you may end up with large number of small files – not easy to keep track. So depending on the scenario and convenience one can have one or more classes per file in Python.
Yes, it can. However, there can only be one public top-level class per . java file, and public top-level classes must have the same name as the source file.
In C++ you can define multiple classes inside of a single file. You will not run into trouble by doing it.
Here are some possible reasons:
An example of roughly equivalent functionality: Java's log4j => a couple of dozen files, ~8000 SLOC. Python logging => 3 files, ~ 2800 SLOC.
There's a mantra, "flat is better than nested," that generally discourages an overuse of hierarchy. I'm not sure there's any hard and fast rules as to when you want to create a new module -- for the most part, people just use their discretion to group logically related functionality (classes and functions that pertain to a particular problem domain).
Good thread from the Python mailing list, and a quote by Fredrik Lundh:
even more important is that in Python, you don't use classes for every- thing; if you need factories, singletons, multiple ways to create objects, polymorphic helpers, etc, you use plain functions, not classes or static methods.
once you've gotten over the "it's all classes", use modules to organize things in a way that makes sense to the code that uses your components.
make the import statements look good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With