【问题标题】:Append code to inherited class method将代码附加到继承的类方法
【发布时间】:2015-04-17 10:12:12
【问题描述】:

您将如何附加到继承对象的方法?比如说:

class ABeautifulClass(GoodClass):
    def __init__(self, **kw):
        # some code that will override inherited code
    def aNewMethod(self):
        # do something

现在我从GoodClass 继承了代码,我将如何将代码附加到继承的方法中。如果我从GoodClass 继承代码,我将如何附加到它,而不是基本上删除它并重写它。这在 Python 中可行吗?

【问题讨论】:

  • 调用父方法,然后做你想做的事情。

标签: python class append


【解决方案1】:

在 Python 中,必须通过 super 关键字显式调用超类方法。所以这取决于你是否这样做,以及你在哪里做。如果您不这样做,那么您的代码将有效地替换父类中的代码;如果您在方法的开头执行此操作,您的代码将有效地附加到它。

def aNewMethod(self):
    value = super(ABeautifulClass, self).aNewMethod()
    ... your own code goes here

【讨论】:

    【解决方案2】:

    尝试使用超级

    class ABeautifulClass(GoodClass):
        def __init__(self, **kw):
            # some code that will override inherited code
        def aNewMethod(self):
            ret_val = super().aNewMethod() #The return value of the inherited method, you can remove it if the method returns None
            # do something
    

    Learn more about super here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 2018-10-26
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      相关资源
      最近更新 更多