Fundamentals 9 min read

Master Python Decorators: From Basics to Advanced Usage

This article explains what Python decorators are, how they work as closures to extend function behavior without altering source code, and provides clear examples—including basic syntax, syntactic sugar with @, execution timing, common use cases, and advanced patterns such as parameterized, multi‑decorator, and class‑based decorators.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Decorators: From Basics to Advanced Usage

Decorators in Python are functions that modify other functions, allowing code to be more concise and Pythonic.

1. Definition of Decorators

They add extra functionality to existing functions without changing the function’s source code or call signature; essentially they are closures.

Do not modify existing function source code

Do not modify existing function call style

Add extra functionality

Distinguish from closures: a closure with a single function‑type argument is a decorator.

2. Example Code

# Define decorator

def decorator(func):
    def inner():
        # Decorate the existing function
        print('已添加登录认证')
        func()
    return inner

def comment():
    print('发表评论')

# Apply decorator
comment = decorator(comment)
# Call unchanged
comment()

3. Syntactic Sugar

Using the @decorator syntax provides a cleaner way to apply a decorator.

# Define decorator

def decorator(func):
    def inner():
        print('已添加登录认证')
        func()
    return inner

@decorator

def comment():
    print('发表评论')

comment()

4. Execution Timing

Decorators are executed immediately after the module is loaded, decorating the target function.

def decorator(func):
    print('装饰器执行了')
    def inner():
        print('已添加登录认证')
        func()
    return inner

@decorator

def comment():
    print('发表评论')

5. Use Cases

5.1 Common Scenarios

Measure function execution time

Log output

5.2 Timing Example

import time

def decorator(func):
    def inner():
        begin = time.time()
        func()
        end = time.time()
        print(f'函数执行完成耗时:{end - begin}')
    return inner

@decorator

def work():
    for i in range(10000):
        print(i)

work()

6. General‑Purpose Decorators

Decorators can handle functions with parameters, return values, variable arguments, and can be implemented as classes.

6.1 Decorating Functions with Parameters

def decorator(func):
    def inner(num1, num2):
        print('正在努力执行加法计算')
        func(num1, num2)
    return inner

@decorator

def add_num(num1, num2):
    result = num1 + num2
    print(f'结果为:{result}')

add_num(1, 2)

6.2 Decorating Functions with Return Values

def decorator(func):
    def inner(num1, num2):
        print('正在努力执行加法计算')
        num = func(num1, num2)
        return num
    return inner

@decorator

def add_num(num1, num2):
    return num1 + num2

result = add_num(1, 2)
print(f'结果为:{result}')

6.3 Decorating Functions with *args and **kwargs

def decorator(func):
    def inner(*args, **kwargs):
        print('正在努力执行加法计算')
        return func(*args, **kwargs)
    return inner

@decorator

def add_num(*args, **kwargs):
    result = sum(args) + sum(kwargs.values())
    return result

result = add_num(1, 2, a=3)
print(f'结果为:{result}')

6.4 Multiple Decorators

def make_div(func):
    print('make_div装饰器执行了')
    def inner():
        return '<div>' + func() + '</div>'
    return inner

def make_p(func):
    print('make_p装饰器执行了')
    def inner():
        return '<p>' + func() + '</p>'
    return inner

@make_div
@make_p

def content():
    return '人生苦短,我用python'

c = content()
print(c)

6.5 Decorators with Arguments

def return_decorator(flag):
    def decorator(func):
        def inner(a, b):
            if flag == '+':
                print('正在努力执行加法计算')
            elif flag == '-':
                print('正在努力执行减法计算')
            func(a, b)
        return inner
    return decorator

@return_decorator('+')

def add_num(a, b):
    print(a + b)

@return_decorator('-')

def sub_num(a, b):
    print(a - b)

add_num(1, 2)
sub_num(1, 2)

6.6 Class‑Based Decorator

class MyDecorator(object):
    def __init__(self, func):
        self.__func = func
    def __call__(self, *args, **kwargs):
        print('马上就有下班啦')
        return self.__func(*args, **kwargs)

@MyDecorator

def show():
    print('快要下雪啦')

show()

7. Application Scenarios

Collect operation or error logs

Validate function permissions

Measure function runtime

Dynamic data retrieval in ORM/DB models

Function result caching

Customize input/output serialization

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.

programmingCode Examplesfunctionsdecoratorsclosure
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.