"""函数装饰器示例"""
def my_decorator(func):
def inner():
print("在函数调用之前执行一些操作")
func() # 调用被装饰的函数
print("在函数调用之后执行一些操作")
return inner
@my_decorator # @my_decorator == say_hello = my_decorator(say_hello)
def say_hello():
print("Hello, 装饰器!")
say_hello() # 调用被装饰的函数
-------------------------------------------------------------------------------
"""类装饰器示例"""
class Foo:
def __call__(self, func):
def inner():
print('running inner function')
func()
return inner
@Foo()
def show():
print('show function')
show()
Python3 Function and Class装饰器
于 2023-10-10 15:50:08 首次发布