python - Construct a object which can be mapped or un packed -
so have (of course true thing more complicated) :
class test(object): = -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 want (again true thing more complex):
> t = test() > dict(t) {'a': 0, 'b': 1} > dict(**t) {'a': 0, 'b': 1}
this work perfectly, fail work if define class subclass of dict, , want, want object behave dict hidden tricks under knees (and again sure makes more sense in real code):
class test(dict): .... same code here ....
in case dict(t)
, dict(**t)
return empty dictionary {}
, [k k in t]
return ['a','b']
.
what miss ? seems need redeclare dict function, though __getitem__, __iter__, __len__, __contains__ , keys
method enough trick. tried redeclare iterkeys, itervalues, copy, get, etc, nothing seems work.
thanks.
class test(dict): = -1 def __init__(self): super(test, self).__init__({"a": 0, "b": 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] t = test() print dict(t) # output: {'a': 0, 'b': 1} print dict(**t) # output: {'a': 0, 'b': 1}
of course, hardcode {'a': 0, 'b': 1}
in class definition not idea.
Comments
Post a Comment