繁体   English   中英

将python2转换为python3 getattribute

[英]converting python2 to python3 getattribute

我的脚本在Python3上遇到了递归循环,我尝试用items替换iteritems items但无法解决问题,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__正在调用hasattr()文档说明状态是通过调用getattr() (因此调用了类的__getattribute__ )。

您不得在__getattribute__调用hasattr()

__getattribute__文档指出了无限递归的潜力,并提供了有关解决方案的指导:

为了避免此方法的无限递归,其实现应始终调用具有相同名称的基类方法以访问其所需的任何属性,例如object。 getattribute (个人,姓名)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM