__getattr__ 在 python 中递归 [英] __getattr__ going recursive in python

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

问题描述

我通过以下方式声明了一个类

I have the declared a class in following way

class A:
    def __init__(self, list_1, list_2):
        self.list1 = list_1
        self.list2 = list_2

    def __getattr__(self, item):
        if item in self.list1: return "It is in list 1"
        elif item in self.list2: return "It is in list 2"
        else: return "It is in neither list 1 nor list 2"

在这里,当我添加 __setattr__self.list1 是递归的,因为 __getattr__ 在每个 self.list1<之后被调用/code> 并且这种递归是不可阻挡的.你能帮我解决这个问题吗?我需要这样实现.

Here when I am adding __setattr__ self.list1 goes recursive, since __getattr__ get called after every self.list1 and this recursion is unstoppable. Can you please help me out with it. I need to implement like this.

谢谢

推荐答案

首先,这是 __getattr__ 的一个完全奇怪的用法,但我假设你知道这一点.

First of all, this is a totally bizarre usage of __getattr__, but I'll assume that you know that.

基本上,问题是 __setattr__ 总是在您每次执行诸如 self.foo = bar 之类的操作时被调用,因此如果您在 __setattr__<中使用它/code> 你最终会得到你得到的递归.您需要做的是将您尝试直接设置的值插入 __dict__ self.__dict__['foo'] = bar.

Basically, the problem is that __setattr__ is always called every time you do something like self.foo = bar, so if you use that within __setattr__ you'll end up with the recursion that you got. What you need to do is insert the value that you're trying to set directly into __dict__ self.__dict__['foo'] = bar.

如果您使用新的样式类(即Aobject 的后代),那么您也可以使用super(A, self).__setattr__(item, value) 甚至只是 object.__setattr__(self, item, value)

If you're using new style classes (i.e. A is a descendant of object), then you could also do super(A, self).__setattr__(item, value) or even just object.__setattr__(self, item, value)

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

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