martineau

wrapping_methods_example.py

Apr 15th, 2016
482
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python3
  2. from types import FunctionType
  3. from functools import wraps
  4.  
  5. def wrapper(method):
  6.     @wraps(method)
  7.     def wrapped(*args, **kwrds):
  8.         """ Adds 1 to the value returned by wrapped method function. """
  9.         # first arg of class methods is class instance -- aka "self"
  10.         class_name = args[0].__class__.__name__
  11.         func_name = method.__name__
  12.         print('calling {}.{}()... '.format(class_name, func_name))
  13.         return method(*args, **kwrds) + 1
  14.     return wrapped
  15.  
  16. class MetaClass(type):
  17.     def __new__(meta, class_name, bases, classDict):
  18.         newClassDict = {}
  19.         for attributeName, attribute in classDict.items():
  20.             if isinstance(attribute, FunctionType):
  21.                 # replace it with a wrapped version
  22.                 attribute = wrapper(attribute)
  23.             newClassDict[attributeName] = attribute
  24.         return type.__new__(meta, class_name, bases, newClassDict)
  25.  
  26. class MyClass(MetaClass('NewBaseClass', (object,), {})):  # creates base class
  27.     def method1(self, arg):
  28.         """ Adds 1 to the value of its argument and returns it. """
  29.         print('MyClass.method1({}) called'.format(arg))
  30.         return arg + 1
  31.  
  32. print('MyClass().method1(40) -> {}'.format(MyClass().method1(40)))
  33.  
  34. # Output:
  35. #
  36. #     calling MyClass.method1()...
  37. #     MyClass.method1(40) called
  38. #     MyClass().method1(40) -> 42
RAW Paste Data