简体   繁体   English

直接从内置类型与其在Python中的包装器类继承

[英]Inheriting directly from a built-in type versus its wrapper class in Python

I'm currently reading Dive Into Python by Mark Pilgrim, and have gotten to the section on inheritance. 我目前正在阅读Mark Pilgrim的Dive Into Python ,并且已经进入了继承一节。 In section 5.5 , Pilgrim mentions the differences between inheriting from the wrapper class UserDict vs inheriting from the built-in dict type. 5.5节中 ,Pilgrim提到了从包装类UserDict继承与从内置dict类型继承之间的区别。

I'm having trouble understanding why anyone would even bother with the wrapper class... What are the benefits of inheriting from the UserDict wrapper class (or any of the other UserXxx classes)? 我很难理解为什么有人甚至会打扰包装器类...从UserDict包装器类(或任何其他UserXxx类)继承的好处是什么?

Your input is much appreciated. 非常感谢您的投入。 Thanks! 谢谢!

You're right: 你是对的:

The need for this class has been largely supplanted by the ability to subclass directly from dict (a feature that became available starting with Python version 2.2). 可以直接从dict继承子类(此功能自Python 2.2版开始可用)已大大取代了对此类的需要。 Prior to the introduction of dict, the UserDict class was used to create dictionary-like sub-classes that obtained new behaviors by overriding existing methods or adding new ones. 在引入dict之前,UserDict类用于创建类似于字典的子类,这些子类通过覆盖现有方法或添加新方法来获得新行为。

Note the first sentence. 注意第一句话。 This comes from the documentation of UserDict. 这来自UserDict的文档

Oh, and in Python 3 it's gone. 哦,在Python 3中不见了。

The wrapper classes have been removed from Python 3, as they haven't been all that useful for a while now. 包装器类已从Python 3中删除,因为它们已经有一段时间没有那么有用了。 The mixin class, UserDict.DictMixin , is a completely different story -- its useful features are now found all over the "abstract base classes" in the collections module (Python 2.6 and 3.*). mixinUserDict.DictMixin是一个完全不同的故事–现在,它的有用功能在collections模块(Python 2.6和3. *)的“抽象基类”中都可以找到。

I found, on the page you linked to, a hint as to the answer: 我在您链接到的页面上找到了有关答案的提示:

In versions of Python prior to 2.2, you could not directly subclass built-in datatypes like strings, lists, and dictionaries. 在2.2之前的Python版本中,您不能直接对诸如字符串,列表和字典之类的内置数据类型进行子类化。 To compensate for this, Python comes with wrapper classes that mimic the behavior of these built-in datatypes: UserString, UserList, and UserDict. 为了弥补这一点,Python附带了包装器类,这些包装器类模拟了以下内置数据类型的行为:UserString,UserList和UserDict。 Using a combination of normal and special methods, the UserDict class does an excellent imitation of a dictionary. 通过使用常规方法和特殊方法的组合,UserDict类可以很好地模仿字典。 In Python 2.2 and later, you can inherit classes directly from built-in datatypes like dict. 在Python 2.2及更高版本中,您可以直接从内置数据类型(如dict)继承类。

In reality, today you probably want to sub-class dict, rather than UserDict. 实际上,今天您可能想对dict进行分类,而不是对UserDict进行分类。

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

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