python常用抽象基类1
from abc import abstractmethod from collections.abc import Container, Sized, Iterable, Iterator from collections.abc import Sequence, Mapping, Set from collections.abc import MutableSequence, MutableMapping, MutableSet from collections.abc import MappingView, ItemsView, KeysView, ValuesView from collections.abc import Callable, Hashable class UserContainer(Container, Sized, Iterable): # 对应len()方法 def __len__(self) -> int: return len(self.items) # 对应in关键字 def __contains__(self, x: object) -> bool: return x in self.items def __init__(self): self.items = list() self.index = 0 def append(self, obj): self.items.append(obj) # 和__iter__一起实现for in语法 def __next__(self): if self.index < len(self.items): v = self.items[self.index] self.index += 1 return v else: raise StopIteration def __iter__(self): return self # Sequence是Container, Sized, Iterable子类 class UserList(Sequence): def __init__(self): self.data = list() self.data.append(1) self.data.append(2) def __len__(self) -> int: return len(self.data) # 实现分片取数[]能力 def __getitem__(self, i: int): return self.data[i] class UserMap(Mapping): def __init__(self): self.data = dict() self.index = 0 self.data['a'] = 1 self.data['b'] = 2 def __len__(self) -> int: return len(self.data) def __iter__(self): return self # 实现v=data[k]取数语法 def __getitem__(self, k): return self.data[k] # 实现data[k]=赋值语法 def __setitem__(self, key, value): self.data[key] = value class UserSet(Set): def __init__(self): self.data = set() self.data.add(6) self.data.add(7) def __contains__(self, x: object) -> bool: return x in self.data def __len__(self) -> int: return len(self.data) def __iter__(self): return self if __name__ == '__main__': u = UserContainer() u.append("u1") u.append("u2") u.append("u3") print("u1" in u) print(len(u)) print("========") for i in u: print(i) print("========") u3 = UserList() print(u3[1]) print("************") for i in u3: print(i) print("************") u4 = UserMap() u4['c'] = 3 print(u4['a']) u5 = UserSet() print(9 in u5)