defmy_decorator(func):defwrapper():print("Something is happening before the function is called.")func()print("Something is happening after the function is called.")return wrapper@my_decoratordefsay_hello():print("Hello!")say_hello()# =========================================================# Replace the decoratordefmy_decorator(func):defwrapper():print("Something is happening before the function is called.")func()print("Something is happening after the function is called.")return wrapperdefsay_hello():print("Hello!")decorated_say_hello =my_decorator(say_hello)decorated_say_hello()
執行結果:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
defscale_and_shift(factor,offset=0):defdecorator(func):defwrapper(*args,**kwargs):returnfunc(*args, **kwargs)* factor + offsetreturn wrapperreturn decorator# Use the decorator with both a factor and an offset.@scale_and_shift(2, offset=3)deffoo(x):return xprint(foo(5))# Output: (5*2) + 3 = 13# Use the decorator with only a factor. The offset defaults to 0.@scale_and_shift(3)defbar(x):return xprint(bar(5))# Output: (5*3) + 0 = 15# =========================================================# 【Replace the decorator】defscale_and_shift(factor,offset=0):defdecorator(func):defwrapper(*args,**kwargs):returnfunc(*args, **kwargs)* factor + offsetreturn wrapperreturn decoratordeffoo(x):return x# Create a new function by applying the decorator manuallyfoo_decorated =scale_and_shift(2, offset=3)(foo)print(foo_decorated(5))# Output: (5*2) + 3 = 13defbar(x):return x# Create a new function by applying the decorator manuallybar_decorated =scale_and_shift(3)(bar)print(bar_decorated(5))# Output: (5*3) + 0 = 15
# 【decorator】defmy_decorator(func):defwrapper():print("Something is happening before the function is called.")func()print("Something is happening after the function is called.")return wrapper@my_decoratordefsay_hello():print("Hello!")say_hello()# =========================================================# 【Replace the decorator】defmy_decorator(func):defwrapper():print("Something is happening before the function is called.")func()print("Something is happening after the function is called.")return wrapperdefsay_hello():print("Hello!")say_hello =my_decorator(say_hello)say_hello()
執行結果:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
Something is happening before the function is called.
Hello!
Something is happening after the function is called.