使用带或不带括号的python装饰器 [英] Using python decorator with or without parentheses

查看:128
本文介绍了使用带或不带括号的python装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,使用带括号和不带括号的相同修饰符 有什么区别?

In Python, what is the difference between using the same decorator with and without parentheses?

例如:

不带括号:

@some_decorator
def some_method():
    pass

带括号:

@some_decorator()
def some_method():
    pass


推荐答案

some_decorator 在第一个代码段中是常规修饰符:

some_decorator in the first code snippet is a regular decorator:

@some_decorator
def some_method():
    pass

等于

some_method = some_decorator(some_method)

另一方面,第二个代码段中的 some_decorator 是可返回的可调用对象装饰者:

On the other hand, some_decorator in the second code snippet is a callable that returns a decorator:

@some_decorator()
def some_method():
    pass

等效于

some_method = some_decorator()(some_method)

正如Duncan在评论中指出的那样,某些装饰器被设计为双向工作。这是这种装饰器的一个非常基本的实现:

As pointed out by Duncan in comments, some decorators are designed to work both ways. Here's a pretty basic implementation of such decorator:

def some_decorator(arg=None):
    def decorator(func):
        def wrapper(*a, **ka):
            return func(*a, **ka)
        return wrapper

    if callable(arg):
        return decorator(arg) # return 'wrapper'
    else:
        return decorator # ... or 'decorator'

pytest.fixture 是一个更复杂的示例。

pytest.fixture is a more complex example.

这篇关于使用带或不带括号的python装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆