Decorator 1

1


def print_info(func):
    def wrapper(*args, **kwargs):
        print('start')
        result = func(*args, **kwargs)
        print('end')
        return result
    return wrapper

def sum(a, b):
    return a + b

f = print_info(sum)
r = f(10, 20)
print(r)

Execution result of 1


start
end
30

The print_info function is a decorator Decorating the sum function.

It's hard to understand if it's written as 1. It is easier to understand if you write as follows. .. ..

Also, the decorator can be reused, so based on that. .. ..

2


def print_info(func):
    def wrapper(*args, **kwargs):
        print('start')
        result = func(*args, **kwargs)
        print('end')
        return result
    return wrapper

@print_info
def sum(a, b):
    return a + b

@print_info
def sub(a, b):
    return a - b

print(sum(10, 20))
print(sub(90, 20))

Execution result of 2


start
end
30
start
end
70

Recommended Posts

Decorator 1
Decorator 2
Decorator
Decorator
MyHDL decorator
Note: Python Decorator
Design Pattern #Decorator
Python function decorator
Write decorator in class
python decorator to retry
Make a function decorator
Summarize Python's @property decorator
Decorator pattern in Java
python decorator usage notes
Use a Property Decorator?
Python decorator operation memo
I tried Python> decorator
Decorate with a decorator