Python中多个相同基类的多重继承

9 投票
1 回答
4269 浏览
提问于 2025-04-17 06:08

我正在努力理解Python中的多重继承。

假设我有一个基础类:

class Structure(object):
    def build(self, *args):
        print "I am building a structure!"
        self.components = args

然后我有两个类是从这个基础类继承的:

class House(Structure):
    def build(self, *args):
        print "I am building a house!"
        super(House, self).build(*args)

class School(Structure):
    def build(self, type="Elementary", *args):
        print "I am building a school!"
        super(School, self).build(*args)

最后,我创建了一个使用多重继承的类:

class SchoolHouse(School, House):
    def build(self, *args):
        print "I am building a schoolhouse!"
        super(School, self).build(*args)

接着,我创建了一个SchoolHouse对象,并在它上面运行了build

>>> sh = SchoolHouse()
>>> sh.build("roof", "walls")
I am building a schoolhouse!
I am building a house!
I am building a structure!

所以我在想——School类发生了什么?有没有办法让Python同时运行这两个类呢?

我特别想知道,因为有很多Django的包提供了自定义的Managers用于模型。但似乎没有办法在不让一个Manager继承另一个的情况下将它们结合起来。能同时导入并使用两个Manager吗?看起来好像不行?

另外,我觉得如果能推荐一些关于Python多重继承的好资料就更好了。我之前做过一些Mixins的工作,真的很喜欢使用它们。我只是想知道,当两个不同的类都继承自同一个基础类时,有没有什么优雅的方法来结合它们的功能。

没错,真是我太傻了。其实一直是个打字错误。我觉得自己很笨。我保证,在实际编程中我总是把正确的类放进去,只有在剪切和粘贴尝试这个的时候才搞错了。

1 个回答

17

你在SchoolHouse里的super()调用写错了。

应该是:

super(School, self).build(*args)

正确的写法是:

super(SchoolHouse, self).build(*args)

撰写回答