gpt4 book ai didi

Python pickle 使用 getattr 进行循环递归?

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

class Test(object):
def __init__(self, a):
self.a = a

def __getattr__(self, name):
return getattr(self.a, name)

from pickle import loads, dumps
loads(dumps((Test(something),)))

我得到了:

      7     def __getattr__(self, name):
----> 8 return getattr(self.a, name)

RuntimeError: maximum recursion depth exceeded

有什么提示吗?

我可以通过更改代码来解决这个问题:

if 'a' in self.__dict__:
return getattr(self.a, name)

但我不想。有更好的解决方案吗?

谢谢

最佳答案

我会使用 getattr() 而不是 __getattr__。这相当于调用 getattr(Test(a).a, name)。这首先转向 a.__getattribute__,如果失败则转向 a.__getattr__

class Test(object):
def __init__(self, a):
self._a = a

def __getattr__(self, name):
a = object.__getattribute__(self, '_a')
return getattr(a, name)

关于Python pickle 使用 getattr 进行循环递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22781872/

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