gpt4 book ai didi

python - Python中具有相同基类的多重继承

转载 作者:太空狗 更新时间:2023-10-30 00:26:59 25 4
gpt4 key购买 nike

我正在努力研究 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。但是,似乎没有一种方法可以将它们组合起来,而无需编写一个或另一个管理器作为继承自另一个管理器。只导入两者并以某种方式使用两者会很好,但看起来无法完成?

另外,我想如果有人指出一本关于 Python 多重继承的入门读物,那会很有帮助。我之前用 Mixins 做过一些工作,并且非常喜欢使用它们。我想我只是想知道当两个不同的类继承自同一基类时,是否有任何优雅的方法来组合它们的功能。

是的,愚蠢的我。这一直是一个错字。我觉得很蠢。我保证,当我在现实生活中 super 时,我总是把正确的类放在正确的类中,只有当我剪切和粘贴来尝试这个时,我才搞砸了。

最佳答案

SchoolHouse 中的 super() 调用是错误的。

它是:

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

应该是:

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

关于python - Python中具有相同基类的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8097877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com