如何在python中引用父方法? [英] how to refer to a parent method in python?

查看:207
本文介绍了如何在python中引用父方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个类(一个是父类,一个是子类)。如果方法也在子类中定义不同,我如何引用父类中的方法?

Suppose I have two classes (one a parent and one a subclass). How do I refer to a method in the parent class if the method is also defined in the subclass different?

这是代码:

class A:
    def __init__(self, num):
        self.value=num
    def f(self, num):
        return self.value+2
class B(A):
    def f(self, num):
        return 7*self.f(num)

在最后一行中,我想用self.f(num)来引用父类A. 命令,而不是B中的方法本身会产生无限递归。提前谢谢你。

In the very last line, I want to refer to the parent class A with the "self.f(num)" command, not the method itself in B which would create an infinite recursion. Thank you in advance.

推荐答案

如果你知道你想要使用A,你也可以用这种方式明确地引用A: / p>

If you know you want to use A you can also explicitly refer to A in this way:

class B(A):
    def f(self,num): 
        return 7 * A.f(self,num)

记住你必须明确地将self参数赋给成员函数Af()

remember you have to explicitly give the self argument to the member function A.f()

这篇关于如何在python中引用父方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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