簡體   English   中英

創建一個被視為列表但具有更多功能的python類?

[英]Create a python class that is treated as a list, but with more features?

我有一個名為dataList的類。 它基本上是一個包含一些元數據的列表---myDataList.data包含(numpy)列表本身,myDataList.tag包含描述等。我希望能夠使myDataList [42]返回myDataList的相應元素。數據,我想讓Numpy等將它識別為一個列表(IE,numpy.asarray(myDataList)返回一個包含myDataList中數據的numpy數組)。 在Java中,這就像將dataList聲明為實現List接口一樣簡單,然后只定義必要的函數。 你會怎么用Python做到這一點?

謝謝。

您可以子類列表並提供其他方法:

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

    def foobar(self):
        return 'foobar'

CustomList繼承了Python普通列表的方法,您可以輕松地讓它實現更多的方法和/或屬性。

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實例並將其用作普通列表。

>>> a = mylist([1,2,3,4])
>>> a
[1,2,3,4]
>>> a[2] = 3                  # access normal list features
>>> a.append(5)               # access normal list features
>>> a
[1,2,3,4,5]
>>> a.tag                     # your custom meta data
'some tag'
>>> a.id                      # your custom meta data
3
>>> a.foobar()                # your custom meta data
'foobar'
>>> a.meta1 = 'some more'     # you can even add more meta data on the fly (which you cannot do in a regular list class)
>>> a.meta1
'some more'                   # your new meta data

定義__len__ __iter____iter__ __getitem__ __iter____iter__以及構成容器類型的其他魔術方法。

例如,簡化范圍實現:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM