gpt4 book ai didi

Python 扩展具有相同方法名的类

转载 作者:太空宇宙 更新时间:2023-11-04 10:45:21 26 4
gpt4 key购买 nike

在 Python 中,如果您有一个扩展 2 个或更多类的类,如果它们都有一个标题为 save 的方法,它如何知道调用哪个类方法?

class File(models.Model, Storage, SomethingElse):

def run(self):
self.save()

如果 Storage 有一个save(),什么是 SomethingElse() 有一个save()?谁能简单解释一下?

最佳答案

Python supports a limited form of multiple inheritance as well. A class definition with multiple base classes looks as follows:

class DerivedClassName(Base1, Base2, Base3): . . .

The only rule necessary to explain the semantics is the resolution rule used for class attribute references. This is depth-first, left-to-right. Thus, if an attribute is not found in DerivedClassName, it is searched in Base1, then (recursively) in the base classes of Base1, and only if it is not found there, it is searched in Base2, and so on.

因此在您的示例中,如果所有 3 个类都有方法 saveFile 的实例将使用 models.Model< 中的方法 save/

关于Python 扩展具有相同方法名的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17747534/

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