I have a generic class (A) which is to be subclassed a lot like this:
class A:
def run(self):
...
self.do_something()
...
#abstract function
def do_something(self):
pass
class B(A):
def do_something(self):
...
The subclasses are in separate files that I’m running directly by adding this code to each file (B is the name of the subclass in the file):
if __name__ == '__main__':
B().run()
My question is, can I avoid having to add this code to all files with the subclasses since the only thing that changes in the code is the class being used (B in the example)?
If your python version is recent enough, you can create a class decorator.
In this case, an indirect one.
should do the job if you define
runifmain()somewhere centrally and just use the@runifmain(__name__)wherever it is needed.