简体   繁体   中英

Python calling extended child method from parent

I'm trying to call a parent method, and then the extended child method from the parent class in python.

Goal: Create a child method, that inherits a Parent. in the Parent's init it calls one of it's own methods. The parent method should do something, then call the child version of the same method (of the same name) to extend the functionality. The child method of the same name will never be called directly. This is for python 2.7

Absolute worst case I can just add more kwargs to modify the functionality of the Parent method_a, but I would rather have it much more abstract. Example code below.

def Parent(object):
  def __init__(self):
    print('Init Parent')
    self.method_a()


  def method_a():
    print('parent method')
    # potentially syntax to call the Child method here
    # there will be several Child classes though, so it needs to be abstract



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


  def method_a():
    print('child method')



obj = Child()


# expected output:
'Init Parent'
'parent method'
'child method'

Thanks!

EDIT: chepner's answer did work (and may be more correct) but the code I was using to test with was wrong, and this behavior does work in python. Python will call Child's method_a function rather than the Parent one, and then in Child's method_a you can call the Parent first with super(Child, self).method_a() and everything will work fine!

# with the same parent method as above'
def Child(Parent):
  def method_a():
  # call the Parent method_a first
  super(Child, self).method_a()
  print('child method')


c = Child()
# output:
'Init parent'
'parent method'
'child method'

This works, but chepner's method might still be more correct (with an abstracted method_a_callback() method in Parent)

The parent class shouldn't rely on or require knowledge about a child class. You can, however, impose a requirement on a child class to implement a certain method.

class Parent:
    def __init__(self):
        print('Init parent')
        self.method_a()

    def method_a(self):
        print('parent method')
        self.method_a_callback()


    # The child should override this to augment
    # the behavior of method_a, rather than overriding
    # method_a entirely.
    def method_a_callback(self):
        pass


class Child(Parent):
    def method_a_callback(self):
        print('child method')

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