Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I create each class in its own .py file?

Tags:

python

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?

like image 688
Sergio Tapia Avatar asked Jan 19 '10 23:01

Sergio Tapia


People also ask

Should each class be in a separate file 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.

How many classes should be in a Python file?

There is no limit on how many classes one can put in a file or a module.

Can you have multiple classes in Python?

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.

Should subclasses be in the same file?

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.


1 Answers

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.

like image 155
Thomas Wouters Avatar answered Sep 21 '22 13:09

Thomas Wouters