上QQ阅读APP看书,第一时间看更新
Decorators
Decorators were added in Python to make function and method wrapping easier to read and understand. A decorator is simply any function that receives a function and returns an enhanced one. The original use case was to be able to define the methods as class methods or static methods on the head of their definition. Without the decorator syntax, it would require a rather sparse and repetitive definition:
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)
Dedicated decorator syntax code is shorter and easier to understand:
class WithDecorators: @staticmethod def some_static_method(): print("this is static method") @classmethod def some_class_method(cls): print("this is class method")
Let's take a look at the general syntax and possible implementations of decorators.