2017-02-14 41 views
2

我的脚本运行到上Python3递归循环,我曾尝试更换iteritemsitems,但它并没有解决问题,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 
+0

你能提供一些测试代码来重现你的问题吗? – cdarke

+0

@cdarke它似乎hasattr(self,'get_'+ attr):通过使用带有AttributeError的try/except子句来修复PY3中的问题 – pietklerks

回答

0

您在这里有无限递归,因为你__getattribute__是通过调用getattr()(因此调用类的__getattribute__)调用hasattr()the documentation状态下工作。

您不能在您的__getattribute__中致电hasattr()

documentation for __getattribute__笔记这个潜力无限循环,并提供有关解决方案的指导:

为了避免这种方法无穷递归,其实施应始终调用基类方法具有相同的名称访问它需要的任何属性,例如对象。 getattribute(self,name)。