如何在 Python 中调用超级构造函数? [英] How to invoke the super constructor in Python?
本文介绍了如何在 Python 中调用超级构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A:
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
B() # output: hello
在我使用过的所有其他语言中,超级构造函数是隐式调用的.如何在 Python 中调用它?我希望 super(self)
但这不起作用.
In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect super(self)
but this doesn't work.
推荐答案
与其他答案一致,有多种方法可以调用超类方法(包括构造函数),但是在 Python-3.x 中该过程已简化:
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
class A(object):
def __init__(self):
print "world"
class B(A):
def __init__(self):
print "hello"
super(B, self).__init__()
Python-3.x
class A(object):
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
super().__init__()
super()
现在等同于 super(<包含类名>, self)
根据 文档.
super()
is now equivalent to super(<containing classname>, self)
as per the docs.
这篇关于如何在 Python 中调用超级构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文