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 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): ...

Get Python: Journey from Novice to Expert now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.