I'm quite new to Python in general.
I'm aware that I can create multiple classes in the same .py file, but I'm wondering if I should create each class in its own .py file.
In C# for instance, I would have a class that handles all Database interactions. Then another class that had the business rules.
Is this the case in Python?
In Java and PHP (although not strictly required), you are expected to write each class on its own file, with file's name is that of the class as a best practice. But in Python, or at least in the tutorials I've checked, it is ok to have multiple classes in the same file.
There is no limit on how many classes one can put in a file or a module.
As all of us know, Python supports multiple inheritance, what means, in Python, a class can inherit features and attributes from multiple classes. MRO or Method Resolution Order is the hierarchy in which base classes are searched when looking for a method in the parent class. There are two types of classes in python.
You don't HAVE to, but generally speaking, yes. Keeping a subclass in the same file would be the exception to the rule. First of all, you shouldn't just pile tons of code into a single file.
No. Typical Python style is to put related classes in the same module. It may be that a class ends up in a module of its own (especially if it's a large class), but it should not be a goal in its own right. And when you do, please do not name the module after the class -- you'll just end up confusing yourself and others about which is which.
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