装饰器(decorator)
Python装饰器的作用是使函数包装与方法包装(一个函数,接受函数并返回其增强函数)变得更容易阅读和理解。最初的使用场景是在方法定义的开头能够将其定义为类方法或静态方法。
不使用装饰器的代码如下所示
类方法不用装饰器的写法
class WithoutDecorators:
def some_static_method():
print("this is static method")
some_static_method = staticmethod(some_static_method)
def some_class_method(cls):
print("this is class method")
some_class_method = classmethod(some_class_method)
函数不用装饰器的写法
def decorated_function():
pass
decorated_function = some_decorator(decorated_function)
如果用装饰器语法重写的话,代码会更简短,也更容易理解:
类方法使用装饰器的写法
class WithDecorators:
@staticmethod
def some_static_method()