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?
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.
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.
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'>
>>>
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