読者です 読者をやめる 読者になる 読者になる

アヤチノオト

覚書のこと

Pythonでlistのように振る舞うclassを書く

import collections

class MyList(collections.MutableSequence):
    def __init__(self, args):
        self.list = list()
        self.extend(list(args))

    def __len__(self):
        return len(self.list)

    def __getitem__(self, key):
        return self.list[key]

    def __delitem__(self, i):
        del self.list[i]

    def __setitem__(self, i, value):
        self.list[i] = value

    def insert(self, i, value):
        self.list.insert(i, value)

    def __str__(self):
        return str(self.list)

    def length(self):
        return len(self.list)

if __name__ == '__main__':
    list = MyList([1,2,3])
    list.append(4)
    print(list)
ls = MyList([1,2,3]) # -> [1,2,3]
ls.append(4)         # -> [1,2,3,4]
ls.pop()             # -> 4
ls.pop(0)            # -> 1
ls                   # -> [2,3]