Python decorators in classes
Codemia Knowledge Hub ·
Introduction
Python decorators can be used both on class methods and as class-based decorators. When decorating methods inside a class, the decorator must account for the self parameter. Built-in decorators like @staticmethod, @classmethod, and @property modify how methods bind to instances. You can also write custom decorators for methods (e.g., for logging, timing, or access control) and implement decorators as classes using the __call__ method.
Built-in Class Decorators
@staticmethod
Removes the implicit self or cls parameter. The method behaves like a regular function that lives in the class namespace:
@classmethod
Receives the class (cls) instead of the instance (self) as the first argument:
cls refers to the class itself, so from_string works correctly with subclasses too.
@property
Defines getter, setter, and deleter methods that look like attribute access:
Custom Decorators on Methods
When decorating a method, the wrapper must accept self as the first argument:
Generic Decorator (Works on Functions and Methods)
Using *args, **kwargs makes a decorator work on both standalone functions and methods:
Decorator with Parameters
To pass arguments to a decorator, add an outer function:
Class-Based Decorators
Implement a decorator as a class with __call__:
Class-Based Decorator on Methods
When used on methods, a class-based decorator needs the descriptor protocol (__get__):
Stacking Multiple Decorators
Decorators execute bottom-up (closest to the function runs first):
Common Pitfalls
- Forgetting
functools.wraps: Without@functools.wraps(func), the decorated function loses its original__name__,__doc__, and__module__. Always usefunctools.wrapsin the wrapper function. - Not accepting
selfin method decorators: A decorator designed for standalone functions breaks on methods becauseselfis passed as the first argument. Use*args, **kwargsto handle both cases. - Class-based decorators failing on methods: A class with
__call__does not work as a method decorator unless it implements__get__(the descriptor protocol). Without it,selffrom the class instance is not passed correctly. - Decorator order matters with stacking:
@auth @log def f()meansauth(log(f)). The outermost decorator runs first on each call but wraps last during decoration. Order affects behavior when decorators interact. - Mutable default state in class decorators: A class-based decorator shares state across all calls. If decorating multiple methods, each gets the same decorator instance only if defined once. Use per-instance storage if isolation is needed.
Summary
- Use
@staticmethod,@classmethod, and@propertyfor standard method behavior modifications - Custom method decorators must handle
self— use*args, **kwargsfor compatibility with both functions and methods - Always use
@functools.wraps(func)to preserve the original function's metadata - Class-based decorators implement
__call__and need__get__for method decoration - Decorators stack bottom-up: the decorator closest to the function wraps it first
Related reading
- Python DeprecationWarning elementwise comparison failed; this will raise an error in the future
- Python dictionary are keys and values always the same order?
- Python Dictionary Comprehension
- Python dictionary from an object's fields
- Python Dijkstra k shortest paths
- python divide by zero encountered in log - logistic regression
- python efficient substring search
- Python ElementTree module How to ignore the namespace of XML files to locate matching element when using the method find, findall
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.