直接从内置类型继承而不是从Python中的包装类继承

2024-09-28 03:16:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读马克·皮尔格林的Dive Into Python,并且已经进入了关于继承的部分。在section 5.5中,Pilgrim提到了从包装器类UserDict继承与从内置dict类型继承之间的区别。在

我很难理解为什么有人会费心于包装类。。。从UserDict包装器类(或任何其他UserXxx类)继承有什么好处?在

非常感谢您的意见。谢谢!在


Tags: 类型费心section内置dict意见区别dive
3条回答

你说得对:

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). 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.

注意第一句话。这来自UserDict的documentation。在

哦,在Python3中它不见了。在

包装器类已经从Python3中删除了,因为它们已经有一段时间没有那么有用了。mixin类,UserDict.DictMixin是一个完全不同的故事,它的有用特性现在在collections模块(python2.6和3.*)中的“抽象基类”中随处可见。在

我在你链接的页面上找到了一个关于答案的提示:

In versions of Python prior to 2.2, you could not directly subclass built-in datatypes like strings, lists, and dictionaries. To compensate for this, Python comes with wrapper classes that mimic the behavior of these built-in datatypes: UserString, UserList, and UserDict. Using a combination of normal and special methods, the UserDict class does an excellent imitation of a dictionary. In Python 2.2 and later, you can inherit classes directly from built-in datatypes like dict.

实际上,今天您可能希望将dict子类,而不是UserDict。在

相关问题 更多 >

    热门问题