[英]__getattr__ going recursive in 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"
Here when I am adding __setattr__
self.list
1 goes recursive, since __getattr__
get called after every self.list1
and this recursion is unstoppable. 这里当我添加
__setattr__
self.list
1会递归,因为__getattr__
会在每个self.list1
之后被调用,这种递归是不可阻挡的。 Can you please help me out with it. 你能帮我解决一下吗? I need to implement like this.
我需要这样实现。
Thanks 谢谢
First of all, this is a totally bizarre usage of __getattr__
, but I'll assume that you know that. 首先,这是
__getattr__
一个完全奇怪的用法,但我会假设你知道这一点。
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. 基本上,问题是
__setattr__
总是叫你每次这样做时self.foo = bar
,因此,如果您使用内__setattr__
你会,你有递归结束。 What you need to do is insert the value that you're trying to set directly into __dict__
self.__dict__['foo'] = bar
. 您需要做的是将您尝试直接设置的值插入
__dict__
self.__dict__['foo'] = bar
。
If you're using new style classes (ie 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)
如果你正在使用新的样式类(即
A
是object
的后代),那么你也可以做super(A, self).__setattr__(item, value)
甚至只是object.__setattr__(self, item, value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.