2
我的腳本運行到上Python3遞歸循環,我曾嘗試更換iteritems
與items
,但它並沒有解決問題,Python2運行正常..有一些變化__getattribute__
我不知道的?轉換python2到python3的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
你能提供一些測試代碼來重現你的問題嗎? – cdarke
@cdarke它似乎hasattr(self,'get_'+ attr):通過使用帶有AttributeError的try/except子句來修復PY3中的問題 – pietklerks