Do I have to override python's list functions?

Viewed 236

I have a class DataSet that inherits from python's list class:

class DataSet(list):

    def __init__(self, *args):
        super(DataSet, self).__init__(*args)

Now I can create an instance of this class and print the type.

data = DataSet([0, 1, 2, 3, 4])
print(type(data))
>>> <class 'DataSet'>

However, when I want to take for example a subset of this DataSet and I print the type, I get:

data2 = data[2:4]
print(type(data2))
>>> <class 'list'>

This happens because I have not overridden the __getitem__ method of list. I know python's list class has a lot of methods that can be overridden in order to use them, but I am a programmer and the only thing I want to do is for all these methods that normally return an instance of type list now return that instance of type DataSet. Is there a method to achieve this, without overriding all these functions? Or do I have to override all these methods manually?

1 Answers

What you asking for is not impossible.it easy to iterate over all functions that return the array and change the output to what you want using a decorator. if you study the function and work on them manually you will learn more.

class DataSet(list):

    def __init__(self, *args):
        super(DataSet, self).__init__(*args)
#that where we must use decorator and loop over all builin functions
def  DataSet_evo(func):
    
    from inspect import signature
    
    def new_func(*args):
     res=func(*args)   
     if type(res)==type([])  :
      return DataSet(res)
     else:
      return res  #for example pop() it return element so it will throw eror as it not list 
         
   
    return new_func

for i in dir(DataSet):
 if i not in ["__init__","__class__"]:   
  try:   
   line="DataSet."+i+"="+"DataSet_evo(list."+i+")"   
   exec(line)
  except:
     pass# for handling .__class__ in dir
   
data = DataSet([0, 1, 2, 3, 4])
print(type(data))        
data2 = data[2:4]
print(type(data2))

Happy coding

Related