Sal Sal - 4 years ago 208
Python Question

Python Best way to break up large class structure: constants and imports

I have very large file which contains multiple classes and want to break them up with each class getting its own file. I also have a file to interface with those classes:


In the end I want something like:


Classes B and C inherit from Class A. What are best practices for doing this? Specifically:

  1. Where do I import libraries? Since Class B is a Class A, can I just import everything in Class A?

  2. If I need something like re in each class, do I need to import it in every class? Will this give me multiple instances of the same library?

  3. Where do I put constants? Can I define CONSTANT_A in Class A and be done with it, or do I need to define that in each file?

Answer Source

You can give each of your classes a file, and then add them all to a package.

For example you have, and each with classes A, B and C respectively. You can package all these classes into a single package abc by moving the files, and into a single folder, abcp and creating an file.

The file may contain something like

from .a import A
from .b import B
from .c import C

so that it would be possible to directly access the classes from the package.

For example, in you can do something like

import abcp

if __name__ == '__main__':
    oa = abc.A()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download