创建一个python类,它被视为一个列表,但是有更多的特性?

2024-04-20 13:01:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为dataList的类。它基本上是一个包含一些元数据的列表---我的数据列表.data包含(numpy)列表本身,myDataList.tag包含一个描述等。我希望能够使myDataList[42]返回我的数据列表.data,我希望Numpy等将其识别为一个列表(即。,阿萨雷(myDataList)返回包含myDataList中数据的numpy数组)。在Java中,这就像声明dataList和实现List接口一样简单,然后只定义必要的函数。在Python中如何实现这一点?在

谢谢。在


Tags: 数据函数numpy声明列表data定义tag
3条回答
class mylist(list):
    def __init__(self, *args, **kwargs):
        super(mylist, self).__init__(*args, **kwargs)       # advantage of using super function is that even if you change the parent class of mylist to some other list class, like your numpy list class, you won`t have to change the remaining code, which is what you would have to do incase of jena`s code snippet.
        # whatever meta data you want to add, add here
        self.tag = 'some tag'
        self.id = 3

    # you can also add custom methods
    def foobar(self):
        return 'foobar'

现在,您可以创建mylist的实例,并使用它们作为普通列表,以及您的附加元数据。在

^{pr2}$

您可以将list子类化并提供其他方法:

class CustomList(list):
    def __init__(self, *args, **kwargs):
        list.__init__(self, args[0])

    def foobar(self):
        return 'foobar'

CustomList继承了Python普通列表的方法,您可以轻松地让它实现更多的方法和/或属性。在

定义__len____getitem____iter__和其他可选的组成container type的魔术方法。在

例如,简化的range实现:

class MyRange(object):
   def __init__(self, start, end):
       self._start = start
       self._end = end
   def __len__(self):
       return self._end - self._start
   def __getitem__(self, key):
       if key < 0 or key >= self.end:
           raise IndexError()
       return self._start + key
   def __iter__(self):
       return iter([self[i] for i in range(len(self))])

相关问题 更多 >