Python 2 __getattr__最大递归深度 [英] Python 2 __getattr__ max recursion depth

查看:68
本文介绍了Python 2 __getattr__最大递归深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我使用以下代码:

for example i use this code:

class A(object):
    def __init__(self):
        self.dict1 = {
            'A': 3,
            'B': self.A}
    def __getattr__(self, key):
        if key in self.dict1:
            return self.dict1[key]
a = A()

,运行时会抛出超过最大递归深度的信息. 有人可以告诉我我在做什么错

and when it's runned it throws maximum recursion depth exceeded. Can someone please tell me what am i doing wrong here

推荐答案

__getattr__方法中对self.dict1的引用会导致再次调用__getattr__,依此类推,从而实现了无限递归.在__getattr__中访问self属性的唯一安全方法是使用对self.__dict__的引用.试试

The reference to self.dict1 inside your __getattr__ method causes __getattr__ to be called again, and so on, hence the infinite recursion. The only safe way to access attributes of self inside __getattr__ is by using references to self.__dict__. Try

def __getattr__(self, key):
    if key in self.__dict__['dict1']:
        return self.__dict__['dict1'][key]

还请注意,缺少else子句将意味着未定义的属性似乎具有值None.

Note also that the absence of an else clause will mean undefined attributes appear to have the value None.

这篇关于Python 2 __getattr__最大递归深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆