Understanding Python Decorators and Their Four Types with Example
This article explains what Python decorators are, describes their four types—function decorating function, function decorating class, class decorating function, and class decorating class—illustrates each with diagrams, and provides a practical example that dynamically passes test case names to a function via a decorator.
Decorators are a Python feature that adds functionality to existing code without modifying its structure.
There are four main types of decorators: function‑decorates‑function, function‑decorates‑class, class‑decorates‑function, and class‑decorates‑class.
Each type is illustrated with diagrams showing the relationship between the target and the decorator.
A concrete example demonstrates how a decorator can dynamically obtain the name of a test case function, assign it to a fixed parameter pvid, and pass it as a keyword argument to a class method.
The example shows the decorator extracting the current function name via get_current_function_name(), checking for a test_ prefix, and using the name when present; otherwise pvid defaults to pvid_test.
Execution results for test_case_1, test_case_2, and a non‑test name illustrate how func_names and pvid are printed.
In summary, the article introduces the four decorator types in Python and provides a practical scenario of a function‑decorating‑class implementation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
