Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple classes in a Python module

Tags:

python

I'm very new to Python (I'm coming from a JAVA background) and I'm wondering if anyone could help me with some of the Python standards. Is it a normal or "proper" practice to put multiple class in a module? I have been working with Django and started with the tutorials and they place their database model classes in the same module. Is this something that is normally done or should I stick with 1 class per module? Is there a reason I would do one over the other?

Hope I'm being clear and not to generic. Thanks to everyone in advance!

like image 260
ralph Avatar asked Apr 14 '10 01:04

ralph


People also ask

Can Python module have multiple classes?

So a module can contain several classes. Whenever you want to use a particular class, import the respective module first and then call the class to make objects.

How do you use multiple classes in Python?

A class can be derived from more than one base class in Python, similar to C++. This is called multiple inheritance. In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance.

Can an object have multiple classes?

An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements.

How many classes can you have in Python?

Everything in Python libraries and other Python applications is either a module or a package of modules. There is no limit on how many classes one can put in a file or a module.


1 Answers

Here is a useful rule of thumb from what I have seen of typical Java projects:

The bottom-most package in Java should be a file in Python

What does that mean? If your Java project was organized:

toplevel/    subproject/         Foo.java         Bar.java    subproject2/         Baz.java         Qux.java 

Then your Python project should look like:

toplevel/     subproject.py <-- put class Foo, Bar here     subproject2.py <-- put class Baz, Qux here 

Things to notice re: organization:

  • Do not use inner classes. Just put classes in the same module
  • By convention, things that start with _ are "private"
  • It's OK to have "public variables"
like image 106
moshez Avatar answered Sep 22 '22 23:09

moshez