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
你有沒有考慮直接對numpy.ndarray進行子類化?這裏似乎有一個很好的概述/教程在這個主題:http://docs.scipy.org/doc/numpy/user/basics.subclassing.html – matt
@matt - 如果你提交作爲答案,我會爲它投票。 。 。 – JoshAdel
@matt - 剛試過這個,它給了我一個令人沮喪的錯誤:當我繼承numpy.ndarray並創建一個新的dataList對象(我編寫了自己的構造函數)時,出現錯誤:「TypeError:需要整數」。我假設我無法覆蓋numpy.ndarray的構造函數?我怎麼做? – Chironex