"""函数装饰器示例"""
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 首次发布
本文详细介绍了Python中的函数装饰器和类装饰器的使用方法,包括如何定义和应用装饰器,以及它们在增强函数功能和封装上的作用。

被折叠的 条评论
为什么被折叠?



