为什么在多重继承中只能调用一个类的init方法 [英] Why in Multiple Inheritance only one class init method get called

查看:118
本文介绍了为什么在多重继承中只能调用一个类的init方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在a.py模块中

class Foo(object):
    def __init__(self):
        self.foo = 20

class Bar(object):
    def __init__(self):
        self.bar = 10

class FooBar(Foo, Bar):
    def __init__(self):
        print "foobar init"
        super(FooBar, self).__init__()
a = FooBar()
print a.foo
print a.bar

在多个继承中,只有一流的init方法被调用. 有什么方法可以在多个继承中调用所有init方法,所以我可以访问所有类实例变量

In multiple inheritances only first class init method getting called. Is there any way to call all init method in multiple inheritances, so I can access all classes instances variable

输出:

foobar init
20
Traceback (most recent call last):
File "a.py", line 16, in <module>
    print a.bar
AttributeError: 'FooBar' object has no attribute 'bar'

无法访问 Bar 类变量栏

推荐答案

class Foo(object):
def __init__(self):
    super(Foo,self).__init__()
    self.foo = 20

class Bar(object):
def __init__(self):
    super(Bar,self).__init__()
    self.bar = 10


class FooBar(Bar,Foo):
def __init__(self):
    print "foobar init"
    super(FooBar,self).__init__()



a = FooBar()
print a.foo
print a.bar

super()调用在每个步骤都以MRO(方法解析顺序)查找/next方法/,这就是为什么Foo和Bar也必须拥有它,否则执行会在Bar的末尾停止.初始化.

The super() call finds the /next method/ in the MRO(method resolution order) at each step, which is why Foo and Bar have to have it too, otherwise execution stops at the end of Bar.init.

这篇关于为什么在多重继承中只能调用一个类的init方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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