我的脚本在 Python3 上运行递归循环,我尝试用 items
替换iteritems
,但它不能解决问题,Python2 运行良好.. 我不知道__getattribute__
有一些变化吗?
class Map(object):
def __init__(self, *args, **kwargs):
for arg in args:
if isinstance(arg, dict):
for k, v in arg.items():
self.__dict__[k] = v
self.__dict__['_' + k] = v
if kwargs:
for k, v in kwargs.items():
self.__dict__[k] = v
self.__dict__['_' + k] = v
def __getattribute__(self, attr):
if hasattr(self, 'get_' + attr):
return object.__getattribute__(self, 'get_' + attr)()
else:
return object.__getattribute__(self, attr)
def get(self, key):
try:
return self.__dict__.get('get_' + key)()
except (AttributeError, TypeError):
return self.__dict__.get(key)
Map(**{'hello': 'world', 'foo': 'bar'}) # infinite recursion
运行时,这将产生:
Traceback (most recent call last):
File "demo.py", line 29, in <module>
Map(**{'hello': 'world', 'foo': 'bar'}) # recursive loop
File "demo.py", line 13, in __init__
self.__dict__[k] = v
File "demo.py", line 17, in __getattribute__
if hasattr(self, 'get_' + attr):
File "demo.py", line 17, in __getattribute__
if hasattr(self, 'get_' + attr):
[...]
RecursionError: maximum recursion depth exceeded
无限递归,因为你的__getattribute__
正在调用文档声明通过调用getattr()
来工作的hasattr()
(从而调用类的__getattribute__
(。
您不得在__getattribute__
中打电话给hasattr()
。
__getattribute__
的文档指出了无限递归的可能性,并提供了有关解决方案的指导:
为了避免此方法中的无限递归,它的实现应始终调用具有相同名称的基类方法,以访问它所需的任何属性,例如对象。getattribute(self, name(.