__setattr__ 在这段 python 代码中做了什么?
这是我的代码:
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
this is my 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']
and the error is :
AttributeError: fun instance has no attribute '__getitem__'
when i change it to :
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
the error is :
RuntimeError: maximum recursion depth exceeded
what can I do, I want get 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是 self.key = ... 调用 __setattr__ ,因此您最终会陷入无限递归。要使用
__setattr__
,您必须以其他方式访问对象的字段。常见的解决方案有两种:The problem is that
self.key = ...
invokes__setattr__
, so you end up in an infinite recursion. To use__setattr__
, you have to access the object's field some other way. There are two common solutions:这是一个错字。
您想要实现特殊方法
__setattr__
,而不是没有特殊含义的__serattr__
。It's a typo.
You want to implement the special method
__setattr__
, and not__serattr__
which has no special meaning.首先,该方法称为
__setattr__()
。这是尝试属性分配的时候。例如,当您执行以下操作时:...使您的特定调用(无限)递归!
更好的方法是从
object
派生类,即所谓的 新样式类 并调用基类:我删除了您的
__getattr__()
实现,因为它没有任何任何价值。Firstly, the method is called
__setattr__()
. It is when an attribute assignment is attempted. Such as when you do:...making your particular call (infinitely) recursive!
A better way to do this would be to derive your class from
object
, a so-called new-style class and call the base class:I removed your
__getattr__()
implementation, since it did nothing of any value.