Guido van Rossum | ae3b3a3 | 1993-11-30 13:43:54 +0000 | [diff] [blame] | 1 | # A more or less complete user-defined wrapper around list objects |
| 2 | |
| 3 | class UserList: |
Guido van Rossum | 2a340b3 | 1999-03-26 16:20:18 +0000 | [diff] [blame] | 4 | def __init__(self, list=None): |
| 5 | self.data = [] |
| 6 | if list is not None: |
| 7 | if type(list) == type(self.data): |
| 8 | self.data[:] = list |
| 9 | else: |
| 10 | self.data[:] = list.data[:] |
| 11 | def __repr__(self): return repr(self.data) |
| 12 | def __cmp__(self, other): |
| 13 | if isinstance(other, UserList): |
| 14 | return cmp(self.data, other.data) |
| 15 | else: |
| 16 | return cmp(self.data, other) |
| 17 | def __len__(self): return len(self.data) |
| 18 | def __getitem__(self, i): return self.data[i] |
| 19 | def __setitem__(self, i, item): self.data[i] = item |
| 20 | def __delitem__(self, i): del self.data[i] |
| 21 | def __getslice__(self, i, j): |
| 22 | i = max(i, 0); j = max(j, 0) |
| 23 | userlist = self.__class__() |
| 24 | userlist.data[:] = self.data[i:j] |
| 25 | return userlist |
| 26 | def __setslice__(self, i, j, other): |
| 27 | i = max(i, 0); j = max(j, 0) |
| 28 | if isinstance(other, UserList): |
| 29 | self.data[i:j] = other.data |
| 30 | elif isinstance(other, type(self.data)): |
| 31 | self.data[i:j] = other |
| 32 | else: |
| 33 | self.data[i:j] = list(other) |
| 34 | def __delslice__(self, i, j): |
| 35 | i = max(i, 0); j = max(j, 0) |
| 36 | del self.data[i:j] |
| 37 | def __add__(self, other): |
| 38 | if isinstance(other, UserList): |
| 39 | return self.__class__(self.data + other.data) |
| 40 | elif isinstance(other, type(self.data)): |
| 41 | return self.__class__(self.data + other) |
| 42 | else: |
| 43 | return self.__class__(self.data + list(other)) |
| 44 | def __radd__(self, other): |
| 45 | if isinstance(other, UserList): |
| 46 | return self.__class__(other.data + self.data) |
| 47 | elif isinstance(other, type(self.data)): |
| 48 | return self.__class__(other + self.data) |
| 49 | else: |
| 50 | return self.__class__(list(other) + self.data) |
| 51 | def __mul__(self, n): |
| 52 | return self.__class__(self.data*n) |
| 53 | __rmul__ = __mul__ |
| 54 | def append(self, item): self.data.append(item) |
| 55 | def insert(self, i, item): self.data.insert(i, item) |
| 56 | def pop(self, i=-1): return self.data.pop(i) |
| 57 | def remove(self, item): self.data.remove(item) |
| 58 | def count(self, item): return self.data.count(item) |
| 59 | def index(self, item): return self.data.index(item) |
| 60 | def reverse(self): self.data.reverse() |
| 61 | def sort(self, *args): apply(self.data.sort, args) |
| 62 | def extend(self, other): |
| 63 | if isinstance(other, UserList): |
| 64 | self.data.extend(other.data) |
| 65 | else: |
| 66 | self.data.extend(other) |