如何在Python中调用超类构造函数?

2024-04-23 19:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

class A:
    def __init__(self):
        print("world")

class B(A):
    def __init__(self):
       print("hello")

B()  # output: hello

在我使用过的所有其他语言中,超级构造函数都是隐式调用的。如何在Python中调用它?我希望super(self)但这不起作用。


Tags: self语言helloworldoutputinitdefclass
3条回答

对于Python2.x旧样式类,可能是这样的:

class A: 
 def __init__(self): 
   print "world" 

class B(A): 
 def __init__(self): 
   print "hello" 
   A.__init__(self)

与其他答案一样,有多种方法可以调用超级类方法(包括构造函数),但是在Python-3.x中,该过程被简化了:

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__()

根据the docs,现在super()等价于super(<containing classname>, self)

super()在新样式类中返回父类对象

class A(object):
    def __init__(self):
        print("world")

class B(A):
    def __init__(self):
        print("hello")
        super(B, self).__init__()

B()

相关问题 更多 >