gpt4 book ai didi

python - __setattr__ 在此 python 代码中做了什么?

转载 作者:行者123 更新时间:2023-11-28 19:51:22 25 4
gpt4 key购买 nike

这是我的代码:

class fun:

def __getattr__(self,key):
return self[key]

def __setattr__(self,key,value):
self[key] = value+1
a = fun()
a['x']=1
print a['x']

错误是:

AttributeError: fun instance has no attribute '__getitem__'

当我把它改成:

class fun:

def __getattr__(self,key):
return self.key

def __setattr__(self,key,value):
self.key = value+1
a = fun()
a.x=1
print a.x

错误是:

RuntimeError: maximum recursion depth exceeded

我能做什么,我想要 2

最佳答案

问题是 self.key = ... 调用了 __setattr__,所以你最终陷入无限递归。要使用 __setattr__,您必须以其他方式访问对象的字段。有两种常见的解决方案:

def __setattr__(self,key,value):
# Access the object's fields through the special __dict__ field
self.__dict__[key] = value+1

# or...

def __init__(self):
# Assign a dict field to access fields set via __[gs]etattr__
self.attrs = {}

def __setattr__(self,key,value):
self.attrs[key] = value+1

关于python - __setattr__ 在此 python 代码中做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5361291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com