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 show the difference from regular decorators:
>>> import functools >>> def plus_one(function): ... @functools.wraps(function) ... def _plus_one(self, n): ... return function(self, n + 1) ... return _plus_one >>> class Spam(object): ... @plus_one ... def get_eggs(self, n=2): ... return n * 'eggs' >>> spam = Spam() >>> spam.get_eggs(3) 'eggseggseggseggs'