2009-01-21 11 views
12

当使用Python的super()做方法链,你必须明确指定你自己的类,例如:为什么在使用super()时必须指定自己的类,并且有办法解决它吗?

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

我一定要指定MyDecorator类的名称作为参数传递给super()。这不是干的。当我现在重新命名我的课程时,我将不得不重新命名它两次。为什么这是以这种方式实施的?有没有办法让两班(或更多)写班级的名字?

回答

6

BDFL同意。 3.0的2.6和PEP 3135 - New SuperPep 367 - New Super

+0

链接到当前版本的PEP:http://www.python.org/dev/peps/pep-3135/ – sth 2009-01-21 19:50:19

+0

没有参数的`super()`不*在Python 2.6.1上工作 – jfs 2009-01-21 20:53:34

11

您的愿望成真:

只需使用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) 
0

您也可避免使用

def __init__(self): 
    super(self.__class__, self) 
    ... 
3

在旧版本的Python编写具体的类名这个答案是错的,尝试:

def _super(cls): 
    setattr(cls, '_super', lambda self: super(cls, self)) 
    return cls 

class A(object): 
    def f(self): 
     print 'A.f' 

@_super 
class B(A): 
    def f(self): 
     self._super().f() 

@_super 
class C(B): 
    def f(self): 
     self._super().f() 

C().f() # maximum recursion error 

从文档代码示例

在Python 2中有一种使用装饰器的方法:

def _super(cls): 
    setattr(cls, '_super', lambda self: super(cls, self)) 
    return cls 

class A(object): 
    def f(self): 
     print 'A.f' 

@_super 
class B(A): 
    def f(self): 
     self._super().f() 

B().f() # >>> A.f 
相关问题