在覆盖方法中使用逻辑从方法返回的Python方式

时间:2019-03-02 19:57:22

标签: python python-2.7 inheritance super

我有一个继承的类,该类使用super()来调用重写的父方法。我想基于父方法中的逻辑从子方法中返回。这是我的实现,但是我想知道是否还有一种更惯用的方式?

class ParentClass:
    def __init__(self, parameter):
        self.parameter = parameter

    def method(self):
        if self.parameter:
            return True
        else:
            # Do more logic here
            pass

class ChildClass(ParentClass, object):
    def __init__(*args):
        ParentClass.__init__(*args)

    def method(self):
        return_from_method = super(ChildClass, self).method()
        if return_from_method:  # Is there a better way to do this?
            print('Returning from method')
            return
        else:
            print('Not returning from method')
            # Do more logic here

a = ChildClass(True)
a.method()
# > 'Returning from method'

0 个答案:

没有答案