简体   繁体   English

Python:扩展“dict”类

[英]Python:Extend the 'dict' class

I have to solve this exercise:我必须解决这个练习:

Python's dictionaries do not preserve the order of inserted data nor store the data sorted by the key. Python 的字典不保留插入数据的顺序,也不存储按键排序的数据。 Write an extension for the dict class whose instances will keep the data sorted by their key value.为 dict 类编写一个扩展,其实例将按键值对数据进行排序。 Note that the order must be preserved also when new elements are added.请注意,添加新元素时也必须保留顺序。

How do I extend dict ?我如何扩展dict Do I need to have access to the source code for the dict type?我是否需要访问dict类型的源代码?

You can either subclass dict or UserDict , since van already talked about UserDict, lets look at dict .您可以将dictUserDict子类化,因为 van 已经谈到了 UserDict,让我们看看dict

Type help(dict) into an interpreter and you see a big list of methods.在解释器中输入help(dict) ,你会看到help(dict)方法。 You will need to override all the methods that modify the dict as well as the methods that iterate over the dict.您将需要覆盖修改 dict 的所有方法以及迭代 dict 的方法。

Methods that modify the dict include __delitem__ , __setitem__ , clear etc.修改字典的方法包括__delitem____setitem__clear等。

Methods that iterate the dict include __iter__ , keys , values , items etc.迭代字典的方法包括__iter__keysvaluesitems等。

This should get you started这应该让你开始

>>> class odict(dict):
...     def __init__(self, *args, **kw):
...         super(odict,self).__init__(*args, **kw)
...         self.itemlist = super(odict,self).keys()
...     def __setitem__(self, key, value):
...          # TODO: what should happen to the order if
...          #       the key is already in the dict       
...         self.itemlist.append(key)
...         super(odict,self).__setitem__(key, value)
...     def __iter__(self):
...         return iter(self.itemlist)
...     def keys(self):
...         return self.itemlist
...     def values(self):
...         return [self[key] for key in self]  
...     def itervalues(self):
...         return (self[key] for key in self)
... 
>>> od = odict(a=1,b=2)
>>> print od
{'a': 1, 'b': 2}
>>> od['d']=4
>>> od['c']=3
>>> print od   # look at the `__str__` and `__repr__` methods 
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> print od.keys()
['a', 'b', 'd', 'c']
>>> print od.values()
[1, 2, 4, 3]

The implementation of dict will not help you with the task. dict 的实现不会帮助你完成任务。 What you want is a class that has the same interface as dict , but a different implementation.您想要的是一个与dict具有相同接口但实现不同的类。 That will require to implement methods like __getitem__ , __setitem__ , etc. If you Google for "ordereddict", you will find a lot of examples. 这将需要实现__getitem____setitem__等方法。如果您在 Google 上搜索“ordereddict”,您会发现很多示例。

If you use python 2.7+, then see collections.OrderedDict .如果您使用 python 2.7+,请参阅collections.OrderedDict
Otherwise, backport (copy the source) or see Recipe 576693: Ordered Dictionary for Py2.4 (Python) .否则,向后移植(复制源代码)或参见Recipe 576693: Ordered Dictionary for Py2.4 (Python)

But if you really need to extend the dict , then start with UserDict , source for which you can find in /lib/UserDict.py of your python distribution ( Lib/collections/__init__.py with Python 3).但是如果你真的需要扩展dict ,那么从UserDict开始,你可以在你的 python 发行版的/lib/UserDict.py中找到它的源代码( Lib/collections/__init__.py with Python 3)。

Good news: the problem is not difficult at all.好消息:这个问题一点都不难。

In order to poke around and see the entrails of a class you can use为了四处看看你可以使用的class的内脏

>>> dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

and help(dict) , which has a very complete interactive documentation, but of course you also have access to the even more complete online documentation .help(dict) ,它有一个非常完整的交互式文档,当然你也可以访问更完整的在线文档

Once you have a grasp of what dict does behind the scenes, you should learn about inheritance in Python .一旦你掌握了dict在幕后做了什么,你就应该了解Python 中的继承

If you get stuck visit this site to get some ideas, but don't copy/paste, your teacher will not see it kindly.如果您遇到困难,请访问此站点以获取一些想法,但不要复制/粘贴,您的老师不会友好地看到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM