Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- from types import FunctionType
- from functools import wraps
- def wrapper(method):
- @wraps(method)
- def wrapped(*args, **kwrds):
- """ Adds 1 to the value returned by wrapped method function. """
- # first arg of class methods is class instance -- aka "self"
- class_name = args[0].__class__.__name__
- func_name = method.__name__
- print('calling {}.{}()... '.format(class_name, func_name))
- return method(*args, **kwrds) + 1
- return wrapped
- class MetaClass(type):
- def __new__(meta, class_name, bases, classDict):
- newClassDict = {}
- for attributeName, attribute in classDict.items():
- if isinstance(attribute, FunctionType):
- # replace it with a wrapped version
- attribute = wrapper(attribute)
- newClassDict[attributeName] = attribute
- return type.__new__(meta, class_name, bases, newClassDict)
- class MyClass(MetaClass('NewBaseClass', (object,), {})): # creates base class
- def method1(self, arg):
- """ Adds 1 to the value of its argument and returns it. """
- print('MyClass.method1({}) called'.format(arg))
- return arg + 1
- print('MyClass().method1(40) -> {}'.format(MyClass().method1(40)))
- # Output:
- #
- # calling MyClass.method1()...
- # MyClass.method1(40) called
- # MyClass().method1(40) -> 42
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement