Monkey patching a class in another module in Python

前端 未结 6 1084
走了就别回头了
走了就别回头了 2020-11-27 12:07

I\'m working with a module written by someone else. I\'d like to monkey patch the __init__ method of a class defined in the module. The examples I have found sh

6条回答
  •  甜味超标
    2020-11-27 12:40

    The following should work:

    import thirdpartymodule_a
    import thirdpartymodule_b
    
    def new_init(self):
        self.a = 43
    
    thirdpartymodule_a.SomeClass.__init__ = new_init
    
    thirdpartymodule_b.dosomething()
    

    If you want the new init to call the old init replace the new_init() definition with the following:

    old_init = thirdpartymodule_a.SomeClass.__init__
    def new_init(self, *k, **kw):
        old_init(self, *k, **kw)
        self.a = 43
    

提交回复
热议问题