Decorating class functions
Decorating class functions is very similar to regular functions, but you need to be aware of the required first argument, self
—the class instance. You have most likely already used a few class function decorators. The classmethod
, staticmethod
, and property
decorators, for example, are used in many different projects. To explain how all this works, we will build our own versions of the classmethod
, staticmethod
, and property
decorators. First, let’s look at a simple decorator for class functions to demonstrate the difference from regular decorators:
>>> import functools
>>> def plus_one(function):
... @functools.wraps(function)
... def _plus_one(self, n, *args):
... return function(self, n + 1, *args)
...
... return _plus_one
>>> class Adder(object):
... @plus_one
... def add(self, a, b=0):
... return a + b
>>> adder = Adder()
>>> adder.add(0)
1
>>...