简体   繁体   English

什么时候适合在 Python 中对内置数据类型进行子类化?

[英]When is it appropriate to Subclass built-in data types in Python?

Overview概述

This question is regarding subclassing built-in data types in Python;这个问题是关于在 Python 中对subclassing built-in data types for example:例如:


class MyList(list):
    def __init__(self, *args):
        super().__init__()


class MyDict(dict):
    def __init__(self, *args):
        super().__init__()



my_list = MyList()
my_dict = MyDict()

Note : This is just an example;注意:这只是一个例子; my question is for any built-in data types in general, not just list and dict data-types.我的问题一般是针对任何built-in data types ,而不仅仅是listdict数据类型。

Questions问题

  1. What are the pros and cons of subclassing built-in data types like this?cons pros什么?
  2. Is this recommended Python practice?这是推荐的 Python 实践吗?
  3. Would there ever be a case to use super() when subclassing built-in data types like this?在对这样的内置数据类型进行子类化时,是否有使用super()的情况?
  4. Can you please give a code examples of how to correctly implement a list and dict built-in data subclass?您能否提供一个代码示例,说明如何正确实现listdict内置数据子类?

My advise is to use UserDict and UserList from collections module as starting point:我的建议是使用collections模块中的UserDictUserList作为起点:

UserDict : https://docs.python.org/3/library/collections.html#userdict-objects用户字典: https : UserDict

UserList : https://docs.python.org/3/library/collections.html#userlist-objects用户列表: https : UserList

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

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