这是我的代码:
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']
Run Code Online (Sandbox Code Playgroud)
而错误是:
AttributeError: fun instance has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)
当我把它改为:
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
Run Code Online (Sandbox Code Playgroud)
错误是:
RuntimeError: maximum recursion depth exceeded
Run Code Online (Sandbox Code Playgroud)
我能做什么,我想得到 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1402 次 |
| 最近记录: |