Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Methods are class attributes - Enhance method (Monkey patching)

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

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