Back
+15 XP
Concept

Method Decorators vs Function Decorators

Decorating class methods requires passing `self` into the wrapper. Using `*args, **kwargs` ensures instance state flows seamlessly to the original method ⚙️.

python
import functools

def audit_method(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        print(f"Running {func.__name__} on {self.name} ⚙️")
        return func(self, *args, **kwargs)
    return wrapper

class Worker:
    def __init__(self, name):
        self.name = name

    @audit_method
    def work(self):
        return "Complete"

w = Worker("Worker-01")
print(w.work())

# 39. Method Decorators vs Function Decorators Decorating class methods requires passing `self` into the wrapper. Using `*args, **kwargs` ensures instance state flows seamlessly to the original method ⚙️. ```python import functools def audit_method(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): print(f"Running {func.__name__} on {self.name} ⚙️") return func(self, *args, **kwargs) return wrapper class Worker: def __init__(self, name): self.name = name @audit_method def work(self): return "Complete" w = Worker("Worker-01") print(w.work()) ``` Because bound methods receive `self` as their first positional argument, generic wrappers must accept `*args, **kwargs` to avoid dropping the instance reference! ⚙️ --- ### Question Why must a method decorator's wrapper forward `*args` to the original callable? 🧠 - [ ] a. To pass the `self` instance reference without breaking method binding ⚙️ - [ ] b. Because Python prohibits keyword arguments on methods - [ ] c. To prevent the method from mutating global variables - [ ] d. To enable C-level pointer arithmetic --- ### Challenge Write decorator `audit_method(func)` that prints `f'Calling {func.__name__} on instance'`, then returns `func(self, *args, **kwargs)`. Decorate method `speak(self, msg)` in class `Bot` that returns `f'Bot: {msg}'`. Call `Bot().speak('hi')`. 🎯 <details> <summary>Solution</summary> ```python import functools def audit_method(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): print(f"Calling {func.__name__} on instance") return func(self, *args, **kwargs) return wrapper class Bot: @audit_method def speak(self, msg): return f"Bot: {msg}" print(Bot().speak("hi")) ``` </details>

Checkpoint

Why must a method decorator's wrapper forward `*args` to the original callable? 🧠

Practice

Write decorator `audit_method(func)` that prints `f'Calling {func.__name__} on instance'`, then returns `func(self, *args, **kwargs)`. Decorate method `speak(self, msg)` in class `Bot` that returns `f'Bot: {msg}'`. Call `Bot().speak('hi')`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks