1

I know of function decorators and class method decorators.

But, is it also possible to decorate classes?

martineau
  • 119,623
  • 25
  • 170
  • 301
Paebbels
  • 15,573
  • 13
  • 70
  • 139

3 Answers3

4

Yes, of course.

A decorator is just a function taking a parameter. That parameter can be a class.

#!/usr/bin/env python3

def decorate(cls):
    print(cls)
    return cls

@decorate
class Foo: pass

This code will work both in python2 and python3:

$ python example.py
__main__.Foo
$ python3 example.py
<class '__main__.Foo'>

As for function decorators, a class decorator can return an arbitrary object. You probably want to return something behaving as the original class. You can also modify the class on the fly and return the class itself.

If you are planning to have parameters for the decorator I suggest you this approach, which IMHO is the most natural (biased suggestion :D).

Community
  • 1
  • 1
Dacav
  • 13,590
  • 11
  • 60
  • 87
0

Yes you can:

def bar(cls):
    print("decorating {}".format(cls))

@bar
class Foo(object):
    pass

Will print:

decorating <class '__main__.Foo'>
ojii
  • 4,729
  • 2
  • 23
  • 34
0

In Python 2.6 or newer, yes. Older versions only support function/method decorators.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358