How to extend Class instance

前端 未结 4 1215
礼貌的吻别
礼貌的吻别 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 06:53

    Yes, it's called monkey-patching.

    This is basically decoration, but done manually after the class is already defined.

    from functools import wraps
    
    def wrapper(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            myFunction()
            return f(*args, **kwargs)
        return wrapped
    
    MyClass.printThis = wrapper(MyClass.printThis)
    

    It will affect all instances of MyClass, even those that were created before the patch was applied.

    If you don't need to dynamically modify runtime behaviour, avoid monkey-patching and prefer to use inheritance to customise behaviour, as suggested in the comments. It's less hacky.

提交回复
热议问题