Python在标准库中是否有装饰器? [英] Does Python have decorators in the standard library?
问题描述
除了 @staticmethod
和 @classmethod
之外?大多数语言都有一些利用大多数语言功能的基本库。
Apart from @staticmethod
and @classmethod
? Most languages have some basic libraries making use of most of the language features.
似乎我发现自己制作的许多装饰器都是很多人会使用的东西,但是我还没有找到任何内置的python装饰器来做到这一点。有这样的东西吗?
It seems that many of the decorators I find myself making are things which tons of people would use, but I haven't found any inbuilt python decorators which do them. Are there such things?
推荐答案
属性通常用作装饰器。
functools 具有通常用作修饰符的几种功能,例如 total_ordering
, update_wrapped
, lru_cache
和包裹
。
functools has several functions normally used as a decorator, such as total_ordering
, update_wrapped
, lru_cache
, and wraps
.
contextlib具有 contextmanager
装饰器。
contextlib has the contextmanager
decorator.
请记住,您可以使用任何功能作为装饰器:
Keep in mind, you can use any function as a decorator:
@decorator
def function(): pass
与
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.)
也可以修饰类,
还有一个装饰列表。在Python Wiki上。其中有些在标准库中,有些不在标准库中。
There is also a list of decorators on the Python Wiki. Some of them are in the standard library, some are not.
这篇关于Python在标准库中是否有装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!