mardi 13 mai 2014

python - construire un objet qui peut être mappé ou un emballé - Stack Overflow


So I have this (of course the true thing is more complicated) :


class test(object):
i = -1

def keys(self):
return ["a", "b"]

def __getitem__(self, item):
return {"a": 0, "b": 1}[item]

def __len__(self):
return 2

def __contains__(self, item):
if item in ["a", "b"]:
return True
return False

def __iter__(self):
return self

def next(self):
self.i += 1
if self.i > 1:
raise StopIteration()

return ["a", "b"][self.i]

What I want to do is this (again the true thing is more complex):


> t = test()
> dict(t)
{'a': 0, 'b': 1}
> dict(**t)
{'a': 0, 'b': 1}

This work perfectly, but fail to work if I define the class as a subclass of a dict, and this is what I want, I want my object to behave like a dict with some hidden tricks under knees (and again sure it makes more sense in the real code):


class test(dict):
.... same code here ....

In this case the dict(t) and dict(**t) will return an empty dictionary {}, but [k for k in t] will return ['a','b'].


What do I miss ? It seems that I do need to redeclare some dict function, I though that __getitem__, __iter__, __len__, __contains__ and keys method was enough to do the trick. I tried to redeclare iterkeys, itervalues, copy, get, etc, but nothing seems to work.


Thanks.



So I have this (of course the true thing is more complicated) :


class test(object):
i = -1

def keys(self):
return ["a", "b"]

def __getitem__(self, item):
return {"a": 0, "b": 1}[item]

def __len__(self):
return 2

def __contains__(self, item):
if item in ["a", "b"]:
return True
return False

def __iter__(self):
return self

def next(self):
self.i += 1
if self.i > 1:
raise StopIteration()

return ["a", "b"][self.i]

What I want to do is this (again the true thing is more complex):


> t = test()
> dict(t)
{'a': 0, 'b': 1}
> dict(**t)
{'a': 0, 'b': 1}

This work perfectly, but fail to work if I define the class as a subclass of a dict, and this is what I want, I want my object to behave like a dict with some hidden tricks under knees (and again sure it makes more sense in the real code):


class test(dict):
.... same code here ....

In this case the dict(t) and dict(**t) will return an empty dictionary {}, but [k for k in t] will return ['a','b'].


What do I miss ? It seems that I do need to redeclare some dict function, I though that __getitem__, __iter__, __len__, __contains__ and keys method was enough to do the trick. I tried to redeclare iterkeys, itervalues, copy, get, etc, but nothing seems to work.


Thanks.


0 commentaires:

Enregistrer un commentaire