简单来说,装饰器的作用是修改其他函数的功能。它其实是一个函数,只是这个函数的输入参数也是函数。你可以简单理解成,当你调用被装饰器装饰的函数时,被装饰的函数仅仅是作为一个传入参数,你实际执行的函数其实是你的装饰器函数。
自定义装饰器直接上demo
# -*- coding: utf-8 -*-
# 定义一个装饰器,内容是打印函数的返回值
def print_test(func):
def _print(*args):
print(f"{func(*args)}")
return _print
# 使用装饰器装饰函数
@print_test
def decorators(param: str):
return f"decorators test: print(‘{param}’)"
if __name__ == '__main__':
decorators("测试自定义装饰器")
执行结果
decorators test: print(‘测试自定义装饰器’)内置的装饰器
以下是个人平时用得比较多的几个类中的装饰器(其实不用装饰器也完全可以得到想要的结果,只是用上看起来比较装逼)
# -*- coding: utf-8 -*-
class TestClass(object):
note = f"这是类成员"
@classmethod
def decorators_classmethod(self):
print(f"classmethod 使得类无需实例化,即可直接调用,亦可直接调用类成员---{self.note}")
@property
def decorators_property(self):
return f"property 创建只读属性,使得方法可以像属性一样被访问(调用时不含括号)"
@staticmethod
def decorators_staticmethod():
print(f"staticmethod 表示静态方法,该修饰词的方法无需输入,也不能使用self")
if __name__ == '__main__':
TestClass.decorators_classmethod()
test = TestClass()
print(test.decorators_property)
test.decorators_staticmethod()
执行结果
classmethod 使得类无需实例化,即可直接调用,亦可直接调用类成员---这是类成员 property 创建只读属性,使得方法可以像属性一样被访问(调用时不含括号) staticmethod 表示静态方法,该修饰词的方法无需输入,也不能使用self



