Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you separate python projects logically into separate files/classes like in C#/Java?

Tags:

python

I'm looking to develop a project in python and all of the python I have done is minor scripting with no regard to classes or structure. I haven't seen much about this, so is this how larger python projects are done?

Also, do things like "namespaces" and "projects" exist in this realm? As well as object oriented principles such as inheriting from other classes?

like image 596
Mark Avatar asked Jan 21 '10 01:01

Mark


People also ask

Should classes be in separate files Python?

A module can consist of multiple classes or functions. As Python is not an OO language only, it does not make sense do have a rule that says, one file should only contain one class. One file (module) should contain classes / functions that belong together, i.e. provide similar functionality or depend on each other.

Can you define 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.

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.

How do you split a class in Python?

Probably the most common approach to spreading a class's code over multiple files is to use subclassing, with the base class in one module, and the (or each) subclass, in its own separate module.


1 Answers

Yes, you can, and you should! :)

Here is a nice introduction to Python Modules (including packages).


Correction: you probably should not put each single class into a separate file (like Java mandates and many C++ places do). The language is pretty lax about it as you can see in the linked tutorial, keep an open eye on other projects, use common sense, and do whatever makes sense to you (or whatever is being done in your team/project - unless it is very wrong).

like image 150
Bandi-T Avatar answered Sep 20 '22 05:09

Bandi-T