tags:

views:

63

answers:

3

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

+1  A: 

__ set/getitem__() are used for indexing. Define them as well.

Ignacio Vazquez-Abrams
+1  A: 
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)

Eli Bendersky
A: 

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.

inspectorG4dget