#!/usr/bin/python3 # ==================================================================== # From: www.youtube.com/watch?v=Opp9AQ90FHw # Title: Python tricks: Using magic (dunder) functions to # create list-like objects # ==================================================================== class names: def __init__(self): self._names = [ 'alice', 'beth', 'charles', 'dave', 'edward', 'fred', 'gail', 'helen', 'ive', 'judy', 'tom' ] # ---- magic dunder function called by len() def __len__(self): return len(self._names) # ---- default function # ---- removes the item from the list def __getitem__(self,key): if isinstance(key,str): return self._names.pop(key) # pop removes items from list raise TypeError(f'Can not get key {key}') # ---- called instead if __getitem__ def __contains__(self,name): return name in self._names # ---- implemented with a generator function def __iter__(self): while self._names: yield self._names.pop() # pop removes items from list # -------------------------------------------------------------------- # ---- main # -------------------------------------------------------------------- if __name__ == '__main__': mymob = names() # ---- example 1 print() print(f'There are {len(mymob)} names in the mob') if 'tom' in mymob: print('tom is in mymob') else: print('tom is no in mymob') print(f'There are still {len(mymob)} names in the mob') # ---- example 2 print() print(f'There are {len(mymob)} names in the mob') for name in mymob: print(name) print(f'There are {len(mymob)} names in the mob')