odoo 中的_register_hook,_patch_method


先给个示例:

    def _register_hook(self):
        """

        """

        def test_patch(self):
            print('call test patch')
            
            raise exceptions.UserError('test patch')

        print('run _register_hook')
        self._patch_method('unlink',test_patch)
  1. _register_hook 在服务启动时就会执行,故可以做很多预操作
  2. _patch_method 可以将原有的方法给替换掉,相当于复写,如果调用了原有的方法,也有点类似于装饰器的功能
  3. 感觉 _patch_method 提供了更灵活的代码处理方式,相对于直接将写代码,可以利用该功能做出不少标准工具.比如审批工具,日志工具.

更高级的写法可以参考auditlog模块