list vs UserList和dict vs UserDict [英] list vs UserList and dict vs UserDict

查看:129
本文介绍了list vs UserList和dict vs UserDict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写这一天,上面哪一个是首选和推荐的(在Python 2和3中)用于子类化?

Coding this day, which of the above is preferred and recommended (both in Python 2 and 3) for subclassing?

我读到 UserList UserDict 已被引入,因为过去列表 dict 不能被子类化,但由于这不是一个问题,是否鼓励使用它们?

I read that UserList and UserDict have been introduced because in the past list and dict couldn't be subclassed, but since this isn't an issue anymore, is it encouraged to use them?

推荐答案

根据你的使用情况,这些天你会直接子类化 list dict 或者您可以将 collections.MutableSequence 集合。 MutableMapping ;这些选项还有 使用 User * 对象

Depending on your usecase, these days you'd either subclass list and dict directly, or you can subclass collections.MutableSequence and collections. MutableMapping; these options are there in addition to using the User* objects.

code> User * 对象已被移动到Python 3中的集合模块;但是使用Python 2 stdlib中的任何代码已经被替换为 collections.abc 抽象基类。即使在Python 2中, UserList UserDict 被扩充集合。* 实现,添加方法 list dict 提供超出基本界面。

The User* objects have been moved to the collections module in Python 3; but any code that used those in the Python 2 stdlib has been replaced with the collections.abc abstract base classes. Even in Python 2, UserList and UserDict are augmented collections.* implementations, adding methods list and dict provide beyond the basic interface.

集合类使您的子类成为一个完整的实现必须实现的更清晰,并且还可以实现较小的子集(例如 collections.Mapping ,实现一个只读映射,或者一个元组类对象的 collections.Sequence

The collections classes make it clearer what must be implemented for your subclass to be a complete implementation, and also let you implement smaller subsets (such as collections.Mapping, implementing a read-only mapping, or collections.Sequence for a tuple-like object).

当您需要实现基本界面以外的所有内容时,应使用 User * 实现;例如如果您需要像 list 一样支持添加,排序,倒转和计数。

The User* implementations should be used when you need to implement everything beyond the basic interface too; e.g. if you need to support addition, sorting, reversing and counting just like list does.

对于其他任何事情,您几乎总是更好地使用集合抽象基类作为基础;内置的类型是针对速度进行了优化的,不是那个子类友好的。例如,您需要覆盖列表之间的每个方法,通常会返回一个新的列表,确保您的子类被返回。

For anything else you are almost always better off using the collections abstract base classes as a basis; the built-in types are optimised for speed and are not that subclass-friendly. For example, you'll need to override just about every method on list where normally a new list is returned, to ensure your subclass is returned instead.

只有在需要使用列表 code>或对象(通过使用 isinstance()进行测试是对类型进行子类化的一个选项来考虑。这就是为什么 collections.OrderedDict dict 的子类。

Only if you need to build code that insists on using a list or dict object (tested by using isinstance() is subclassing the types an option to consider. This is why collections.OrderedDict is a subclass of dict, for example.

这篇关于list vs UserList和dict vs UserDict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆