简体   繁体   中英

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

Overview

This question is regarding subclassing built-in data types in Python; 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.

Questions

  1. What are the pros and cons of subclassing built-in data types like this?
  2. Is this recommended Python practice?
  3. Would there ever be a case to use super() when subclassing built-in data types like this?
  4. Can you please give a code examples of how to correctly implement a list and dict built-in data subclass?

My advise is to use UserDict and UserList from collections module as starting point:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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