I want to print 'eee fff {'e':'eee','f':'fff'}',how can i get it. (it is about __setattr__)
the next is my code:
class a:
w={}
def __setattr__(self,name,value):
self.w[name]=value
def __getattr__(self,name)开发者_高级运维:
return self.w[name]
b=a()
b.e='eee'
b['f']='fff'
print b.e,b['f'],b.w
#error
what is the difference between b.e and b['f']. thanks
class MyClass(object):
def __init__(self):
self.w = {}
def __setitem__(self, k, v):
self.w[k] = v
def __getitem__(self, k):
return self.w[k]
mc = MyClass()
mc['aa'] = 12
print mc['aa']
setitem/getitem is for indexed access (with square brackets) like shown above. setattr/getattr is for attribute access (i.e. mc.aa)
__ set/getitem__() are used for indexing. Define them as well.
You have not defined any method/attribute called self.e
If instead, you were to say self.w[e] = 'eee'
, then you're errors should disappear.
精彩评论