我在装饰类中看到无限递归:
def my_decorator():
def class_decorator(cls):
class NewClass(cls):
@classmethod
def func(cls):
print "decorator"
super(NewClass, cls).func()
return NewClass
return class_decorator
class B(object):
@classmethod
def func(cls):
print "Root"
@my_decorator()
class A(B):
@classmethod
def func(cls):
print "func"
super(A, cls).func()
x = A()
x.func()
输出:
decorator
func
func
func
func
... <lots of 'func'> ...
lots of these:
File "test.py", line 22, in func
super(A, cls).func()
File "test.py", line 22, in func
super(A, cls).func()
File "test.py", line 22, in func
super(A, cls).func()
RuntimeError: maximum recursion depth exceeded while calling a Python object
没有装饰器,它返回:
func
Root
...正如预期的那样。
这是怎么回事?
最佳答案
在你装饰了原来的A
之后,相当于:
A = my_decorator()(A)
名称A
指的是新创建的NewClass
,它也继承了原来的A
,不是原始的 A
。因此 super(A, cls).func
总是解析为 super(NewClass, cls).func
,即 A.func
。
展开装饰器并将结果分配给一个不同的名称,您会得到正确的行为:
X = my_decorator()(A)
x = X()
x.func()
给出:
decorator
func
Root
关于python - 装饰器中的无限递归(类似乎是从自身继承的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32462558/