One class per file?
tony.meyer at gmail.com
Sun Oct 5 06:58:52 CEST 2008
>> The book "Code Complete" recommends that you put only one class in a
>> source file, which seems a bit extreme for me.
IMO this is a misunderstanding (by the author). In Python, a file is
not equivalent to a class, it is equivalent to a module. A module
might contain a single class or many, just as a class might contain a
single method or many. You can tell that files are not classes,
because you have have variables, methods, etc at the module level,
outside of class definitions.
If all of the module's functionality is in a single class, then of
course the file only contains one class. If the module's
functionality is split over many classes (or no classes at all), then
the file will not contain exactly one class. Rigidly putting every
class in a separate file would mean that the next level higher than
classes wouldn't be modules, it would be packages.
> Consider this. You're slogging through some code in a large project
> to debug a problem when you come upon the line (in pseudo-code):
> foo = SomeClass::SomeFunction(bar)
> You want to go look at the source for SomeClass. What file do you
> open to
> find it? If you follow the "one class per file" rule, the answer is
> it's in SomeClass.xxx!
Alternatively, most IDEs will let you go to the source very simply.
If you don't have that facility available, then you just do "import
More information about the Python-list