fork download
  1. class at_time:
  2. actions = {}
  3.  
  4. def __init__(self, time_of_day):
  5. self.time_of_day = time_of_day
  6.  
  7. def __call__(self, func):
  8. self.actions.setdefault(func.__qualname__, {})[self.time_of_day] = func
  9. return self
  10.  
  11. def __set_name__(self, owner, name):
  12. self.name = name
  13.  
  14. def __get__(self, obj, objtype):
  15. def wrapper(time_of_day):
  16. for cls in objtype.__mro__:
  17. if func := self.actions.get(
  18. '.'.join((cls.__qualname__, self.name)), {}).get(time_of_day):
  19. return func(obj)
  20. raise ValueError(f'No {self.name} found in the {time_of_day} time')
  21. return wrapper
  22.  
  23. class PersonalChef():
  24. @at_time('morning')
  25. def cook(self):
  26. print("Cooking breakfast")
  27.  
  28. @at_time('evening')
  29. def cook(self):
  30. print("Cooking dinner")
  31.  
  32. class PersonalChefUK(PersonalChef):
  33. @at_time('evening')
  34. def cook(self):
  35. print("Cooking supper")
  36.  
  37. PersonalChef().cook('morning')
  38. PersonalChef().cook('evening')
  39. PersonalChefUK().cook('morning')
  40. PersonalChefUK().cook('evening')
Success #stdin #stdout 0.04s 9512KB
stdin
Standard input is empty
stdout
Cooking breakfast
Cooking dinner
Cooking breakfast
Cooking supper