Built-in Decorators

Python comes with several built-in decorators. The big three are:

  • @classmethod
  • @staticmethod
  • @property

There are also decorators in various parts of Python’s standard library. One example would be functools.wraps. We will be limiting our scope to the three above though.

@classmethod and @staticmethod

I have never actually used these myself, so I did a fair bit of research. The <*@classmethod>* decorator can be called with with an instance of a class or directly by the class itself as its first argument. According to the Python documentation: It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. The primary use case of a @classmethod decorator that I have found in my research is as an alternate constructor or helper method for initialization.

The <*@staticmethod>* decorator is just a function inside of a class. You can call it both with and without instantiating the class. A typical use case is when you have a function where you believe it has a connection with a class. It’s a stylistic choice for the most part.

It might help to see a code example of how these two decorators work:

Get hands-on with 1200+ tech skills courses.