开发者

Avoid if __name__ == '__main__' in Python subclasses to be run using function from parent

开发者 https://www.devze.com 2023-04-04 11:13 出处:网络
I have a generic class (A) which is to be subclassed a lot like this: class A: def run(self): ... self.do_something()

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.

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.


What about adding an extra function to your main class A?

class A():
    ..
    def __RunIfMain__(self,name):
        if name == '__main__':
            self.run()

In your subclass you'd have one line less:

class B(A):
  ..

B().__RunIfMain__(__name__)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号