這是我的代碼:__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
對不起,請參閱更新 – zjm1126 2011-03-19 09:42:36