Python decorators in classes
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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
.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 courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.