Class Decorators, Inheritance, super(), and maximum recursion

前端 未结 5 1774
故里飘歌
故里飘歌 2020-12-31 19:52

I\'m trying to figure out how to use decorators on subclasses that use super(). Since my class decorator creates another subclass a decorated class seems to pre

5条回答
  •  礼貌的吻别
    2020-12-31 20:46

    Basically, you can see the problem after entering your code sample at the interactive Python prompt:

    >>> SubClassAgain
    
    

    i.e., the name SubClassAgain is now bound (in global scope, in this case) to a class that in fact isn't the "real" SubClassAgain, but a subclass thereof. So, any late-bound reference to that name, like the one you have in its super(SubClassAgain, call, will of course get the subclass that's masquerading by that name -- that subclass's superclass is of course "the real SubClassAgain", whence the infinite recursion.

    You can reproduce the same problem very simply without decoration, just by having any subclass usurp its base-class's name:

    >>> class Base(object):
    ...   def pcl(self): print 'cl: %s' % self.__class__.__name__
    ... 
    >>> class Sub(Base):
    ...   def pcl(self): super(Sub, self).pcl()
    ... 
    >>> Sub().pcl()
    cl: Sub
    >>> class Sub(Sub): pass
    ... 
    

    now, Sub().pcl() will cause infinite recursion, due to the "name usurpation". Class decoration, unless you use it to decorate and return the same class you get as an argument, is systematic "name usurpation", and thus incompatible with uses of the class name which absolutely must return the "true" class of that name, and not the usurper (be that in self or otherwise).

    Workarounds -- if you absolutely must have both class decoration as usurpation (not just class decoration by changes in the received class argument), and super -- basically need protocols for cooperation between the usurper and the possible-usurpee, such as the following small changes to your example code:

    def class_decorator(cls):
        class _DecoratedClass(cls):
        _thesuper = cls
            def __init__(self):
                return super(_DecoratedClass, self).__init__()
        return _DecoratedClass
    
       ...
    
    @class_decorator
    class SubClassAgain(BaseClass):
        def print_class(self):
        cls = SubClassAgain
        if '_thesuper' in cls.__dict__:
            cls = cls._thesuper
            super(cls, self).print_class()
    

提交回复
热议问题