gpt4 book ai didi

python - 装饰器中的无限递归(类似乎是从自身继承的)

转载 作者:太空宇宙 更新时间:2023-11-03 11:26:27 25 4
gpt4 key购买 nike

我在装饰类中看到无限递归:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com