简体   繁体   English

在装饰器中定义函数

[英]defining functions in decorator

Why does this not work? 为什么这不起作用? How can I make it work? 我怎样才能使它工作? That is, how can I make gu accessible inside my decorated function? 也就是说,如何在我的装饰功能中使用gu?

def decorate(f):
    def new_f():
        def gu():
            pass
        f()
    return new_f

@decorate
def fu():
    gu()

fu()

Do I need to add gu to a dictionary of defined functions somehow? 我是否需要以某种方式将gu添加到已定义函数的字典中? Or can I add gu to the local namespace of f before calling it? 或者我可以在调用之前将gu添加到f的本地名称空间吗?

If you need to pass gu to fu you need to do this explicitly by parameters: 如果你需要将gu传递给fu你需要通过参数显式地执行此操作:

def decorate(f):
    def new_f():
        def gu():
            pass
        f(gu)
    return new_f

@decorate
def fu(gu):
    gu()

fu()

gunew_f函数的本地函数,它是decorate函数的本地函数。

gu() is only defined within new_f(). gu()仅在new_f()中定义。 Unless you return it or anchor it to new_f() or something else, it cannot be referenced from outside new_f() 除非您将其返回或将其锚定到new_f()或其他内容,否则无法从外部引用new_f()

I don't know what you're up to, but this scheme seems very complex. 我不知道你在做什么,但这个方案似乎很复杂。 Maybe you can find a less complicated solution. 也许你可以找到一个不太复杂的解决方案

In principle you can create a new function using the same code as the old one but substituting the global scope with an amended one: 原则上,您可以使用与旧代码相同的代码创建新函数,但使用修改后的代码替换全局范围:

import new

def with_bar(func):
    def bar(x):
        return x + 1
    f_globals = func.func_globals.copy()
    f_globals['bar'] = bar
    return new.function(func.func_code, f_globals,
                        func.func_name, func.func_defaults, func.func_closure)

@with_bar
def foo(x):
    return bar(x)

print foo(5) # prints 6

In practice you really should find a better way to do this. 在实践中,你真的应该找到一个更好的方法来做到这一点。 Passing in functions as parameters is one option. 将函数作为参数传递是一种选择。 There might be other approaches too, but it's hard to tell what would fit without a high-level problem description. 可能还有其他方法,但如果没有高级别的问题描述,很难说出什么是合适的。

Why not make your decorator a class rather than a function? 为什么不让你的装饰者成为一个类而不是一个函数呢? It's apparently possible, as I discovered when I looked through the help for the property builtin. 这显然是可能的,正如我在寻找内置property的帮助时所发现的那样。 (Previously, I had thought that you could merely apply decorators to classes, and not that the decorators themselves could be classes.) (以前,我曾经认为你只能将装饰器应用于类,而不是装饰器本身可以是类。)

(Of course, gu would have to be a method of the class or of an inner class.) (当然, gu必须是班级或内部班级的方法。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM