簡體   English   中英

Python從父級調用擴展子方法

[英]Python calling extended child method from parent

我試圖調用父方法,然后從python的父類中調用擴展子方法。

目標:創建一個繼承父對象的子方法。 在父級的init中,它調用自己的方法之一。 父方法應該執行某些操作,然后調用同一方法(具有相同名稱)的子版本以擴展功能。 同名的子方法永遠不會直接調用。 這是針對python 2.7

絕對最差的情況是,我可以添加更多的kwarg來修改Parent method_a的功能,但我希望它更加抽象。 下面的示例代碼。

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'

謝謝!

編輯:chepner的答案確實有效(並且可能更正確),但是我用來測試的代碼是錯誤的,並且此行為確實在python中有效。 Python 調用Child的method_a函數而不是Parent函數,然后在Child的method_a中,您可以首先使用super(Child,self).method_a()調用Parent,一切正常!

# 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'

這可行,但是chepner的方法可能仍然更正確(在Parent中使用抽象的method_a_callback()方法)

父類不應依賴或要求有關子類的知識。 但是,您可以對子類施加要求以實現某種方法。

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM