3
class SimpleClass(object):
     def A(self, *args):
          ...
     def B(self, *args):
          ...
     def C(self, *args):
          ...

Is there anyway to catch the arguments passed to A, B, C, modify those arguments and pass the modified arguments onto A, B, C without having to modify the existing code ?

Edit:

Answer: use a class decorator, that decorates all methods of the class with another decorator.

The method decorator performs the pre-processing.

Quan Vuong
  • 1,919
  • 3
  • 14
  • 24
  • You can do with with [decorators](http://stackoverflow.com/questions/739654/how-to-make-a-chain-of-function-decorators-in-python). – kennysong Jan 03 '17 at 18:45
  • but would that require adding decorators to each class method ? – Quan Vuong Jan 03 '17 at 18:46
  • oh you can create a decorator for that class that decorate each class method with another decorator http://stackoverflow.com/questions/5481623/python-dynamically-add-decorator-to-class-methods-by-decorating-class – Quan Vuong Jan 03 '17 at 18:47

1 Answers1

0

Try this:

from types import FunctionType

class SimpleClass(object):
    def A(self, *args):
        pass
    def B(self, *args):
        pass
    def C(self, *args):
        pass


def methods(cls):
    """List of all method in class."""
    return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]

def args_decorator(method):
    """Decorator for SimpleClass methods"""
    def wrapper(self, *args):
        new_args = list(args)
        # change new_args here
        return method(self, *new_args)
    return wrapper


for method in methods(SimpleClass):
    setattr(SimpleClass, method, args_decorator(SimpleClass.__dict__[method]))

Though if you can change your SimpleClass I'd suggest using decorator like so:

def args_decorator(method):
    def wrapper(self, *args):
        new_args = list(args)
        # change new_args here
        return method(self, *new_args)
    return wrapper

class SimpleClass(object):
    @args_decorator
    def A(self, *args):
        pass
    @args_decorator
    def B(self, *args):
        pass
    @args_decorator
    def C(self, *args):
        pass
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48