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

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

问题描述

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

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

B()
hello

在所有其他语言中,我使用的super构造函数是隐式调用的。如何在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

推荐答案

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

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

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