How to extend Class instance

前端 未结 4 1256
礼貌的吻别
礼貌的吻别 2021-01-20 06:50

MyClass is defined in module.py. There is no way we can modify it. But we do know the Class definition looks like this:

class MyCla         


        
4条回答
  •  耶瑟儿~
    2021-01-20 07:00

    This is an alternative to wim's answer that also involves monkey-patching. However, it does it through functionality provided by unittest.mock. The advantage of this approach is that a context manager is used to automatically apply and remove the patch within a limited scope:

    from unittest import mock
    
    # This class would be defined in some third-party library
    class MyClass:
        def method(self, msg):
            print('from method:', msg)
    
    
    def function(msg):
        print('from function:', msg)
    
    
    old_method = MyClass.method
    
    
    def new_method(self, msg):
        old_method(self, msg)
        function(msg)
    
    
    # The patch is only applied within this scope
    with mock.patch.object(MyClass, 'method', new_method):
        foo = MyClass()
        foo.method('message with patched')
    
    # By this point MyClass is "back to normal"
    print('---')
    foo.method('message with original')
    

    Output

    from method: message with patched
    from function: message with patched
    ---
    from method: message with original
    

提交回复
热议问题