Subclass list without deep copy

I want to subclass listadd some function to it, for example my_func.

Is there a way to do this without copying the entire list, i.e. make a shallow copy when creating the object MyList, and let it MyListrefer to the same list as the one used to build it?

class MyList(list):
    def my_func(self):
        # do some stuff
        return self


l1 = list(range(10))
l2 = MyList(l1)

print(l1)
print(l2)

l1[3] = -5

print(l1)
print(l2)
+4
source share
1 answer

Pretty sure that this is not possible with a subclass list. This is possible with a subclass (just in Python ): collections.UserListUserList2

from collections import UserList

class MyList(UserList):

    def __init__(self, it=None):
        # keep reference only for list instances
        if isinstance(it, list):
            self.data = it
        else:
            super().__init__(it)

    def my_func(self):
        # do some stuff
        return self

, UserList data , , it :

, :

l1 = list(range(10))
l2 = MyList(l1)

print(l1, l2, sep='\n')
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

:

l1[3] = -5

data, l1, , :

print(l1, l2, sep='\n')
[0, 1, 2, -5, 4, 5, 6, 7, 8, 9]
[0, 1, 2, -5, 4, 5, 6, 7, 8, 9]
+4

Source: https://habr.com/ru/post/1655990/


All Articles