关键Python基础知识

getattr

  1. def call_hook(self, hook_name):
  2. for hook in self._hooks:
  3. getattr(hook, hook_name)(self)

使用字符串获取对象的属性

代码

  1. import sys
  2. class HOOK:
  3. def before_breakfast(self, runner):
  4. print('{}:吃早饭之前晨练30分钟'.format(sys._getframe().f_code.co_name))
  5. def after_breakfast(self, runner):
  6. print('{}:吃早饭之前晨练30分钟'.format(sys._getframe().f_code.co_name))
  7. def before_lunch(self, runner):
  8. print('{}:吃午饭之前跑上实验'.format(sys._getframe().f_code.co_name))
  9. def after_lunch(self, runner):
  10. print('{}:吃完午饭午休30分钟'.format(sys._getframe().f_code.co_name))
  11. def before_dinner(self, runner):
  12. print('{}: 没想好做什么'.format(sys._getframe().f_code.co_name))
  13. def after_dinner(self, runner):
  14. print('{}: 没想好做什么'.format(sys._getframe().f_code.co_name))
  15. def after_finish_work(self, runner, are_you_busy=False):
  16. if are_you_busy:
  17. print('{}:今天事贼多,还是加班吧'.format(sys._getframe().f_code.co_name))
  18. else:
  19. print('{}:今天没啥事,去锻炼30分钟'.format(sys._getframe().f_code.co_name))
  20. def test_s(self, x):
  21. print(x)
  22. class Runner(object):
  23. def __init__(self, ):
  24. pass
  25. self._hooks = []
  26. def register_hook(self, hook):
  27. # 这里不做优先级判断,直接在头部插入HOOK
  28. self._hooks.insert(0, hook)
  29. def call_hook(self, hook_name):
  30. for hook in self._hooks:
  31. getattr(hook, hook_name)(self)
  32. def run(self):
  33. print('开始启动我的一天')
  34. self.call_hook('before_breakfast')
  35. self.call_hook('after_breakfast')
  36. self.call_hook('before_lunch')
  37. self.call_hook('after_lunch')
  38. self.call_hook('before_dinner')
  39. self.call_hook('after_dinner')
  40. self.call_hook('after_finish_work')
  41. print('~~睡觉~~')
  42. # from MyHook import HOOK
  43. # from MyRunner import Runner
  44. runner = Runner()
  45. hook = HOOK()
  46. runner.register_hook(hook)
  47. runner.run()