Monkey patching a class in another module in Python

前端 未结 6 1085
走了就别回头了
走了就别回头了 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:47

    Dirty, but it works :

    class SomeClass2(object):
        def __init__(self):
            self.a = 43
        def show(self):
            print self.a
    
    import thirdpartymodule_b
    
    # Monkey patch the class
    thirdpartymodule_b.thirdpartymodule_a.SomeClass = SomeClass2
    
    thirdpartymodule_b.dosomething()
    # output 43
    

提交回复
热议问题