防止在子构造函数中调用在父构造函数中调用的方法

时间:2020-02-11 19:12:38

标签: python python-3.x oop

假设我有一个父类和一个从父类继承的子类。

class Parent:
    def __init__(self)
    stubborn()

class Child():
      def __init__(self):
      super().__init__(self)

我不希望在我调用父构造函数时调用顽固方法 在儿童班。我该如何处理?

2 个答案:

答案 0 :(得分:2)

您可以定义classmethod中的Parent,检查您是否在Parent中,然后使用该值来确定是否呼叫stubborn

class Parent:
    def __init__(self):
        if self.is_parent():
            self.stubborn()
    @classmethod
    def is_parent(cls):
        return cls is Parent
    def stubborn(self):
        print("stubborn called")

class Child(Parent): pass

p = Parent() # stubborn called
c = Child() # no output

答案 1 :(得分:0)

如果不实际更改该功能或parent.__init__(),您将无法在stubborn()中对其进行任何操作。

但是,作为孩子,您可以暂时将其设为存根来阻止stubborn()方法做任何重要的事情:

class Child():
    def __init__(self):
        old_stubborn = self.stubborn
        self.stubborn = lambda:None  # stub function that does nothing
        super().__init__(self)
        # put stubborn() back to normal
        self.stubborn = old_stubborn