Does Python have decorators in the standard library?

前端 未结 4 641
太阳男子
太阳男子 2021-02-18 17:38

Apart from @staticmethod and @classmethod? Most languages have some basic libraries making use of most of the language features.

It seems that

4条回答
  •  误落风尘
    2021-02-18 17:47

    property is usually used as a decorator.

    functools has several functions normally used as a decorator, such as total_ordering, update_wrapped, lru_cache, and wraps.

    contextlib has the contextmanager decorator.

    Keep in mind, you can use any function as a decorator:

    @decorator
    def function(): pass
    

    is just the same as

    def function(): pass
    function = decorator(function)
    

    In order to be useful, they generally need to be expecting a callable as an argument and they need to return a callable object. (property is an exception to the second part of that.)

    Classes can also be decorated, in exactly the same way.

    There is also a list of decorators on the Python Wiki. Some of them are in the standard library, some are not.

提交回复
热议问题