gpt4 book ai didi

python - 我可以使用函数结果的属性作为装饰器吗?

转载 作者:太空狗 更新时间:2023-10-30 02:34:09 25 4
gpt4 key购买 nike

我用 Python 为自己制作了一个简单的事件系统,我发现每次触发事件的方式几乎都一样:要么在调用结束时,要么在调用之前。感觉这将是一个装饰师的好东西。这是我正在使用的代码:

from functools import wraps

def fires(event):
"""
Returns a decorater that causes an `Event` to fire immediately before the
decorated function is called
"""
def beforeDecorator(f):
"""Fires the event before the function executes"""
@wraps(f)
def wrapped(*args, **kargs):
event.fire(*args, **kargs)
return f(*args, **kargs)
return wrapped

def afterDecorator(f):
"""Fires the event after the function executes"""
@wraps(f)
def wrapped(*args, **kargs):
result = f(*args, **kargs)
event.fire(*args, **kargs)
return result
return wrapped

# Should allow more explicit `@fires(event).uponCompletion` and
# `@fires(event).whenCalled`
afterDecorator.onceComplete = afterDecorator
afterDecorator.whenCalled = afterDecorator

return afterDecorator

有了这段代码,我就可以成功地写出:

@fires(myEvent)
def foo(y):
return y*y

print func(2)

一切正常。当我尝试写这个时,问题就来了:

@fires(myEvent).onceComplete
def foo(y):
return y*y

print func(2)

这给了我一个语法错误。复杂的装饰器是否有一些特殊的语法?解析器是否在第一组括号后停止?

最佳答案

不,根据 grammar specification ,不可能:

funcdef        ::=  [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suitedecorators     ::=  decorator+decorator      ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINEdotted_name    ::=  identifier ("." identifier)*parameter_list ::=  (defparameter ",")*                    (  "*" [parameter] ("," defparameter)*                    [, "**" parameter]                    | "**" parameter                    | defparameter [","] )parameter      ::=  identifier [":" expression]defparameter   ::=  parameter ["=" expression]funcname       ::=  identifier

装饰器的末尾必须有圆括号

关于python - 我可以使用函数结果的属性作为装饰器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9845574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com