小编Spe*_*tor的帖子

强制子类在重写时调用父方法

我很好奇是否有一种方法可以强制(从Parent类)强制父类方法在被重写时从子类调用.

例:

class Parent(object):

    def __init__(self):
        self.someValue=1

    def start(self):
        ''' Force method to be called'''
        self.someValue+=1
Run Code Online (Sandbox Code Playgroud)

我希望我的孩子Child类做的正确实现将是:

class ChildCorrect(Parent):

    def start(self):
        Parent.start(self)
        self.someValue+=1
Run Code Online (Sandbox Code Playgroud)

但是,有没有办法强制开发Child类的开发人员专门调用(不仅仅覆盖)Parent类中定义的'start'方法,以防他们忘记调用它:

class ChildIncorrect(Parent):

    def start(self):
        '''Parent method not called, but correctly overridden'''
        self.someValue+=1
Run Code Online (Sandbox Code Playgroud)

此外,如果这不是最佳做法,那么还有什么选择呢?

python class

23
推荐指数
3
解决办法
7351
查看次数

标签 统计

class ×1

python ×1