如何调用超级构造函数? [英] How to invoke the super constructor?

查看:96
本文介绍了如何调用超级构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

B()
hello

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

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.

推荐答案

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

super() returns a parent-like object in new-style classes:

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

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

B()

这篇关于如何调用超级构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆