Decorate class
- Python course
- Expert
- Lesson 5/47
- 5 min
Learn to wrap all methods with a class decorator.
What is a class decorator?
A class decorator is a function that takes a class, modifies it and returns it. When you write @add_greet Python first creates class User, then calls add_greet(User).
Inside the decorator you can add new methods or wrap existing ones. You add members with cls.new_method = func. Finally you return cls. This is clearer than a metaclass: the class is fully built before you change it.
Wrapping all methods
A class decorator can iterate every method in a class and wrap it. You get the namespace dict with vars(cls) and select methods with callable(v).
You wrap each method in a wrapper function to add logging or timing. This pattern is more intuitive than a metaclass; the @decorator line makes the intent explicit. But wrapping every method needs care; you may want to skip dunder methods like __init__.
Practice Write the greet decorator
Write a class decorator named add_greet taking cls. Inside it define a greet(self) method returning "merhaba". Attach it with cls.greet = greet and return cls. Write a User class tagged with @add_greet. Create an instance and print greet().
Starter code
# Write the add_greet decorator
# apply it to User
# print the greet callSample solution
# Write the add_greet decorator
def add_greet(cls):
def greet(self):
return "merhaba"
cls.greet = greet
return cls
@add_greet
class User:
pass
u = User()
print(u.greet())Expected output
merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the decorator definition
def add_greet(____):
cls.greet = lambda self: "merhaba"
return cls
def add_greet(cls):
cls.greet = lambda self: "merhaba"
return cls
Explanation: The decorator receives the class object as cls.
2 What does a class decorator receive?
@add_greet
class User:
pass- The class name
- An instance
- The class object Correct answer
- A list of methods
Explanation: A class decorator receives and returns the class object.
3 Match class decorator concepts
| Term | Meaning |
|---|---|
@decorator |
Wraps the class |
cls |
The class object |
vars(cls) |
Namespace dict |
wrapper |
Wrapping function |