python中如何引用父方法?
假设我有两个类(一个是父类,一个是子类)。如果子类中也定义了不同的方法,如何引用父类中的方法?
代码如下:
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 中的方法本身,这会创建无限递归。先感谢您。
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?
Here is the code:
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)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果你知道你想使用 A,你也可以通过这种方式显式引用 A:
记住你必须显式地将 self 参数传递给成员函数 Af()
If you know you want to use A you can also explicitly refer to A in this way:
remember you have to explicitly give the self argument to the member function A.f()
使用
super
:或者在 python 3 中,它只是:
Use
super
:Or in python 3, it's just:
与其他答案一致,有多种方法可以调用超类方法(包括构造函数),但是在 Python-3.x 中,该过程已被简化:
Python-2.x
Python-3.x
super()
现在相当于super(<包含类名>, self)
,根据 文档。In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:
Python-2.x
Python-3.x
super()
is now equivalent tosuper(<containing classname>, self)
as per the docs.为什么不保持简单呢?
Why not keep it simple?
你可以使用 super 或者如果你可以更明确地做这样的事情。
you can use super or if you can be more explicit and do something like this.
查看我的答案 致电家长Python 中子类的类方法?。
这与这里的其他一些(不使用 super )略有不同。
Check out my answer at Call a parent class's method from child class in Python?.
It's a slight twist on some others here (that don't use super).