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 prevent the use of super()
when it changes the className
passed to super(className, self)
. Below is an example:
def class_decorator(cls):
class _DecoratedClass(cls):
def __init__(self):
return super(_DecoratedClass, self).__init__()
return _DecoratedClass
class BaseClass(object):
def __init__(self):
print "class: %s" % self.__class__.__name__
def print_class(self):
print "class: %s" % self.__class__.__name__
bc = BaseClass().print_class()
class SubClass(BaseClass):
def print_class(self):
super(SubClass, self).print_class()
sc = SubClass().print_class()
@class_decorator
class SubClassAgain(BaseClass):
def print_class(self):
super(SubClassAgain, self).print_class()
sca = SubClassAgain()
# sca.print_class() # Uncomment for maximum recursion
The output should be:
class: BaseClass
class: BaseClass
class: SubClass
class: SubClass
class: _DecoratedClass
Traceback (most recent call last):
File "class_decorator_super.py", line 34, in <module>
sca.print_class()
File "class_decorator_super.py", line 31, in print_class
super(SubClassAgain, self).print_class()
...
...
RuntimeError: maximum recursion depth exceeded while calling a Python object
Does anyone know of a way to not break a subclass that uses super()
when using a decorator? Ideally I'd like to reuse a class from time to time and simply decorate it w/out breaking it.