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
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:
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
It's a typo.
You want to implement the special method __setattr__
, and not __serattr__
which has no special meaning.
Firstly, the method is called __setattr__()
. It is when an attribute assignment is attempted. Such as when you do:
self[key] = value+1
...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:
class fun(object):
def __setattr__(self,key,value):
super(fun, self).__setattr__(key, value + 1)
a = fun()
a.x=1
print a.x
I removed your __getattr__()
implementation, since it did nothing of any value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.