我必须覆盖python的列表函数吗?



我有一个类DataSet,它继承自python的list类:

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

现在我可以创建这个类的一个实例并打印类型。

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

然而,当我想以这个DataSet的子集为例并打印类型时,我得到:

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

发生这种情况是因为我没有覆盖list__getitem__方法。我知道python的list类有很多方法可以被重写以使用它们,但我是一名程序员,我唯一想做的就是所有这些通常返回list类型实例的方法现在都返回DataSet类型的实例。有没有一种方法可以在不覆盖所有这些功能的情况下实现这一点?还是必须手动覆盖所有这些方法?

您想要的不是不可能的。使用decorator迭代所有返回数组的函数并将输出更改为您想要的值很容易。如果你研究函数并手动操作,你会学到更多。

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

快乐编码

最新更新