O'Reilly logo

Mastering Python by Rick van Hattem

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required