How can I share a template class to inherit classes in nested packages? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How can I share a template class to inherit classes in nested packages?

Hello! I have a similar project with nested packages: System: __init__.py screen.py timehandler.py Controls: __init__.py event.py mouse.py keyboard.py Each file consists of a class. Example for screen.py: class Screen: ... I've discovered that the classes have lot of similarities and I could save many lines of code by inheriting these classes with a shared template class. I would want to make a python file for the template class, which could be imported in each file before their class declaration. Example for screen.py: from template import TemplateClass class Screen(TemplateClass):: ... But I don't want to make an identical template class in each package. How can I make all the classes to be inherited from the template class? * I only want to make 1 file for the template class. * I don't want to change the project structure.

8th Jun 2020, 12:39 PM
Seb TheS
Seb TheS - avatar
3 Answers
+ 6
About importing from various packages or sub / parent folders you should also check this: https://stackoverflow.com/a/50194143/1222951
8th Jun 2020, 2:47 PM
Tibor Santa
Tibor Santa - avatar
+ 5
Hi my friend, One possible way is to use keyword args for the instance parameters (I think this is the simplest) and call the super class constructor from each child. This can work if you don't have very complex inheritance hierarchy or tricky MRO... https://code.sololearn.com/cNOn9s5fK6HO/?ref=app
8th Jun 2020, 2:30 PM
Tibor Santa
Tibor Santa - avatar
+ 2
Tibor Santa Thanks, but I didn't find a practical solution.
8th Jun 2020, 8:14 PM
Seb TheS
Seb TheS - avatar