Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store each class in a separate file python

I'm looking into organizing my modules and classes. All the time I collect my related classes in a relevant module so I can do things like:

from vehicles.car import engine

In directory vehicles there is a file named car which contains class engine. Clear.

Now I'm looking into the possibility that I can store a class in a file. So I can do something like:

from filters import air

and the air class is a file on its own. However it's not clear to me how I can have a class named air which is stored into its own file called air.py

If filters.py contained all my classes then this import would work, but that's not what I want.

Any tips or pointers?

like image 352
jay_t Avatar asked Jan 30 '12 20:01

jay_t


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.

Can I have multiple classes in one Python file?

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.


1 Answers

Create a directory called filters, and files filters/__init__.py and filters/air.py.

In filters/__init__.py, have: from air import air, and in filters/air.py, define the class air.

Then:

$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from filters import air
>>> air
<class 'filters.air.air'>
>>> 
like image 103
ben w Avatar answered Sep 21 '22 16:09

ben w