kra*_*r65 28 python constructor class multiple-inheritance super
我只是潜入一些更高级的python主题(好吧,至少先进了我).我现在正在阅读有关多继承以及如何使用super()的内容.我或多或少地理解了使用超级函数的方式,但是(1)这样做会有什么问题?:
class First(object):
def __init__(self):
print "first"
class Second(object):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
First.__init__(self)
Second.__init__(self)
print "that's it"
Run Code Online (Sandbox Code Playgroud)
关于super(),Andrew Kuchlings关于Python Warts的论文说:
当Derived类从多个基类继承并且其中一些或全部具有init 方法时,super()的使用也将是正确的
所以我重写了上面的例子如下:
class First(object):
def __init__(self):
print "first"
class Second(object):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
super(Third, self).__init__(self)
print "that's it"
Run Code Online (Sandbox Code Playgroud)
但是,这只运行它可以找到的第一个initFirst
.(2)可以super()
用来运行init的First
和Second
,如果是的话,如何运行?运行super(Third, self).__init__(self)
两次只运行First.init()两次..
增加一些混乱.如果继承类的init()函数采用不同的参数,该怎么办?例如,如果我有这样的东西怎么办:
class First(object):
def __init__(self, x):
print "first"
class Second(object):
def __init__(self, y, z):
print "second"
class Third(First, Second):
def __init__(self, x, y, z):
First.__init__(self, x)
Second.__init__(self, y, z)
print "that's it"
Run Code Online (Sandbox Code Playgroud)
(3)如何使用super()向不同的继承类init函数提供相关参数?
欢迎所有提示!
PS.由于我有几个问题,我把它们做成了大胆的编号.
Gui*_*ume 12
对于问题2,您需要在每个班级中调用super:
class First(object):
def __init__(self):
super(First, self).__init__()
print "first"
class Second(object):
def __init__(self):
super(Second, self).__init__()
print "second"
class Third(First, Second):
def __init__(self):
super(Third, self).__init__()
print "that's it"
Run Code Online (Sandbox Code Playgroud)
对于问题3,无法完成,您的方法需要具有相同的签名.但你可以忽略父句中的一些参数或使用关键字参数.