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

air*_*tyh 14 python multiple-inheritance

使用Python super()进行方法链接时,必须明确指定自己的类,例如:

class MyDecorator(Decorator):
    def decorate(self):
        super(MyDecorator, self).decorate()
Run Code Online (Sandbox Code Playgroud)

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

nos*_*klo 11

你的愿望成真:

只需使用python 3.0.在它你只是使用super()它确实super(ThisClass, self).

文档在这里.文档中的代码示例:

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