简体   繁体   中英

Prevent a method that is called in the parent constructor from being called in the child constructor

Suppose I have a parent class and a child class that inherits from the parent.

class Parent:
    def __init__(self)
    stubborn()

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

I do not want the stubborn method to be called anytime I call the parent constructor in the child class. How do I approach this?

You can define a classmethod of Parent that checks whether or not you are in Parent , then use that to determine whether to call 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

You wouldn't be able to do anything about it in parent.__init__() without actually changing that function or stubborn() .

But, as the child, you could stop the stubborn() method from doing anything important by temporarily making it a stub:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM