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)?
The way to "avoid" inheritance here would be to rename _private_var and make it a class-private name. i.e. __private_var . If you do this, running your code will cause an AttributeError: 'Child' object has no attribute '_Parent__private_var' (note the _Parent prefix automatically added).
In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
__main__ is the name of the module, here as you are directly executing it, its being considered as a script and all scripts have the name __main__ in Python. There's a . in between because Fraction is an attribute of the script __main__ , the module; and belongs to the module level scope.
The process of creating a subclass of a class is called inheritance. All the attributes and methods of superclass are inherited by its subclass also. This means that an object of a subclass can access all the attributes and methods of the superclass.
If your python version is recent enough, you can create a class decorator.
In this case, an indirect one.
def runifmain(mainname):
def deco(clas):
if mainname == '__main__':
clas().run()
return clas
return deco
@runifmain(__name__)
class B(A):
[...]
should do the job if you define runifmain()
somewhere centrally and just use the @runifmain(__name__)
wherever it is needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With