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
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.