Fundamentals 2 min read

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.

360 Tech Engineering
360 Tech Engineering
360 Tech Engineering
Understanding Python Decorators and Their Four Types with Example

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonprogrammingfundamentalsDecoratorexample
360 Tech Engineering
Written by

360 Tech Engineering

Official tech channel of 360, building the most professional technology aggregation platform for the brand.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.