python - 为什么我在使用 super() 时必须指定我自己的类,有没有办法绕过它?

标签 python multiple-inheritance

使用Python的super()做方法链时,必须显式指定自己的类,例如:

class MyDecorator(Decorator):
    def decorate(self):
        super(MyDecorator, self).decorate()

我必须指定我的类 MyDecorator 的名称作为 super() 的参数。这不是干的。当我现在重命名我的类(class)时,我将不得不重命名它两次。为什么要这样实现?有没有办法避免两次(或多次)写类名?

最佳答案

在 Python 3.0 中,您可以使用 super(),它等同于 super(ThisClass, self)

文档 here .文档中的代码示例:

class C(B):
    def method(self, arg):
        super().method(arg)    
        # This does the same thing as: super(C, self).method(arg)

关于python - 为什么我在使用 super() 时必须指定我自己的类,有没有办法绕过它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/466611/

相关文章:

c++ - 为什么下面的类有一个虚拟表?

java - java中如何避免多重继承

prolog - Flora-2 钻石传承

python - Amazon SQS 队列中的重复消息

Python 3 : Getting TypeError: Slices must be integers. .. 但我相信它们

python - 读取 6.9GB 的文件导致段错误

c++ - "import"从基类定义一个函数来实现抽象接口(interface)(C++中的多重继承)

Python 异步 : unreferenced tasks are destroyed by garbage collector?

python - Django assertTemplateUsed() 使用 Jinja 模板抛出异常

java - 为什么要使用接口(interface),多重继承与接口(interface),接口(interface)的好处?