[Python-Dev] Possible wrong behavior of the dict?

2015年3月17日 12:07:17 -0700

Hello!
In order to explain, let define subclass of dict:
class Pair:
 def __init__(self, key, val):
 self.key = key
 self.val = val
class MyDict(dict):
 #
 def __init__(self, *args, **kwds):
 if len(args) > 1:
 raise TypeError('Expected at most 1 arguments, but got %d' %
len(args))
 for key, val in args[0]:
 self[key] = val
 for key, val in kwds.items():
 self[key] = val
 def __getitem__(self, key):
 pair = dict.__getitem__(key)
 return pair.value
 def __setitem__(self, key, val):
 if key in self:
 pair = dict.__getitem__(key)
 pair.value = value
 else:
 pair = Pair(key, val)
 dict.__setitem__(self, key, pair)
 def values(self):
 for key in self:
 p = dict.__getitem__(self, key)
 yield p.value
 def items(self):
 for key, p in dict.__iter__(self):
 yield p.key, p.value
The simple test give me strange result:
>>> d = MyDict([('a', 1), ('b', 2), ('c', 3)])
>>> dict(d)
{'a': <__main__.Pair at 0x104ca9e48>,
 'b': <__main__.Pair at 0x104ca9e80>,
 'c': <__main__.Pair at 0x104ca9eb8>}
instead of {'a':1, 'b':2, 'c':3}.
Is this right behavior of the dict?
---
Zaur Shibzukhov
_______________________________________________
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to