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

前端 未结 5 1811
故里飘歌
故里飘歌 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:39

    Are you sure you want to use a class decorator and not simply inheritance? For instance, instead of a decorator to replace your class with a subclass introducing some methods, perhaps you want a mixin class and to use multiple inheritance to create the final class?

    This would be accomplished by something like

    class MyMixIn(object):
        def __init__(self):
            super(MyMixIn, self).__init__()
    
    class BaseClass(object):
        def __init__(self):
            print "class: %s" % self.__class__.__name__
        def print_class(self):
            print "class: %s" % self.__class__.__name__
    
    class SubClassAgain(BaseClass, MyMixIn):
        def print_class(self):
            super(SubClassAgain, self).print_class()
    
    sca = SubClassAgain()
    sca.print_class() 
    

提交回复
热议问题