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

514 投票
7 回答
400210 浏览
提问于 2025-04-15 20:08
class A:
    def __init__(self):
        print("world")

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

B()  # output: hello

在我接触过的其他编程语言中,父类的构造函数是自动调用的。那么在Python中,应该怎么手动调用呢?我本来以为可以用 super(self),但这样做并没有效果。

7 个回答

53

在Python 2.x的旧式类中,它的写法是这样的:

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

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

super() 是一个用来获取父类对象的函数,特别是在新的类风格中使用:

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

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

B()
454

根据其他回答,有多种方法可以调用父类的方法(包括构造函数),不过在Python 3中,这个过程变得简单了很多:

Python 3

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

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

Python 2

在Python 2中,你需要使用稍微复杂一点的方式来调用,写作 super(<包含类名>, self),这和 super() 的效果是一样的,具体可以参考文档

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

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

撰写回答