[英]What does __setattr__ do in this python code?
这是我的代码:
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
这是一个错字。
你想实现特殊方法__setattr__
,而不是没有特殊含义的__serattr__
。
首先,该方法称为__setattr__()
。 是在尝试进行属性分配时。 比如当你这样做时:
self[key] = value+1
...让你的特定电话(无限)递归!
更好的方法是从object
派生你的类,一个所谓的新式类并调用基类:
class fun(object):
def __setattr__(self,key,value):
super(fun, self).__setattr__(key, value + 1)
a = fun()
a.x=1
print a.x
我删除了你的__getattr__()
实现,因为它没有做任何任何值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.