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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With