Methods are class attributes - Enhance method (Monkey patching)



examples/oop/enhance/shapes.py
class Circle():
    def __init__(self, x, y, r):
        self.x = x
        self.y = y
        self.r = r

    def area(self):
        print('in area')
        return self.r * self.r * 3.14

examples/oop/enhance/enhance_method.py
from shapes import Circle
from tools import add_debug

x = Circle(2, 3, 4)
print(x.area())
print('-----')

add_debug(Circle, 'area')

print(x.area())
# print('-----')
# print(x.area.__name__)

in area
50.24
-----
Before method
in area
After method
50.24


examples/oop/enhance/tools.py
import functools

def add_debug(cls, method):
    original = getattr(cls, method)
    @functools.wraps(original)
    def debug(*args, **kwargs):
        print("Before method")
        result = original(*args, **kwargs)
        print("After method")
        return result
    setattr(cls, method, debug)