class A:
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
B() # output: hello
在我使用过的所有其他语言中,超级构造函数都是隐式调用的.在Python中如何调用它?我希望是super(self)
,但这不起作用.
class A:
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
B() # output: hello
在我使用过的所有其他语言中,超级构造函数都是隐式调用的.在Python中如何调用它?我希望是super(self)
,但这不起作用.
与其他答案一样,在Python-3中,有多种方法可以调用超类方法(包括构造函数).x简化了流程:
Python-3.x
class A(object):
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
super().__init__()
Python-2.x
在python 2中.x、 您必须调用稍微详细一点的版本super(<containing classname>, self)
,它相当于super()
as/the docs.
class A(object):
def __init__(self):
print "world"
class B(A):
def __init__(self):
print "hello"
super(B, self).__init__()