在不更改名称的情况下向父类方法添加其他功能 [英] Adding extra functionality to parent class method without changing its name

查看:70
本文介绍了在不更改名称的情况下向父类方法添加其他功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班级,一个父级,另一个孩子。

I have two classes one parent and other child.

class Parent(object):

    def __init__(self):
        #does something

    def method_parent(self):
        print "Parent"

class Child(Parent):

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

    def method_parent(self):
        print "Child"

继承父对象后,我想修改父方法 method_parent 该方法的原始功能并向该方法添加一些额外的代码行。

After inheriting the parent I want to modify Parent method method_parent keeping the original functionality of that method and adding some extra lines of code to that method.

我知道我可以创建一个新方法,例如

I know that I can create a new method like

def method_child(self):
    self.method_parent()
    #Add extra lines of code to perform something 

但是我想使用方法的原始名称。我无法复制该方法的源代码,因为该方法来自 C 模块

But I want to use the original name of method. I can't copy the source for that method because, the method is from a C module

我想要的达到这样的目的

what I want to achieve is something like this

def method_parent():
    #do parent_method stuff
    #do extra stuff

有可能吗?

推荐答案

您始终可以使用 super()函数从父级调用代码。它提供了对父级的引用。因此,要调用 parent_method(),应使用 super()。parent_method()

You can always call code from the parent using the super() function. It gives a reference to the parent. So, to call parent_method(), you should use super().parent_method().

下面是一个代码段(适用于python3),显示了如何使用它。

Here's a code snippet (for python3) that shows how to use it.

class ParentClass: 
    def f(self): 
        print("Hi!"); 

class ChildClass(ParentClass): 
    def f(self):
        super().f(); 
        print("Hello!"); 

在python2中,您需要使用额外的参数调用super: super(ChildClass ,自我)。因此,摘要将变为:

In python2, you need to call super with extra arguments: super(ChildClass, self). So, the snippet would become:

class ParentClass: 
    def f(self): 
        print("Hi!"); 

class ChildClass(ParentClass): 
    def f(self):
        super(ChildClass, self).f(); 
        print("Hello!"); 

如果您呼叫 f() ChildClass的实例,它将显示:嗨!你好!。

If you call f() on an instance of ChildClass, it will show: "Hi! Hello!".

如果您已经用Java编写过代码,则基本上是相同的行为。
您可以随时随地呼叫super。在一种方法中,通过init函数,...

If you already coded in java, it's basically te same behaviour. You can call super wherever you want. In a method, in the init function, ...

还有其他方法可以做到但是不太干净。例如,您可以这样做:

There are also other ways to do that but it's less clean. For instance, you can do:

ParentClass.f(self) 

调用父类的f函数。

这篇关于在不更改名称的情况下向父类方法添加其他功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆