简体   繁体   English

传入装饰的参数 function

[英]Argument passing in decorated function

A simple decorator that does nothing can be done like follows:一个什么都不做的简单装饰器可以像下面这样完成:

def decorator(func):
    return func # don't need to call!

@decorator
def print_word(word='python'):
    print (word)

And that will run fine:这将运行良好:

>>> print_word()
python

But then if I wrap that in an inner function, it is called liked so:但是,如果我将其包装在内部 function 中,则称为如下:

def decorator(func):
    def _func(*args, **kwargs):
        print ("Args: %s | Kwargs: %s" % (args, kwargs))
        return func(*args, **kwargs) # <== Here I need to "call" it with ()
    return _func

@decorator
def print_word(word='python'):
    print (word)

>>> print_word('ok')
Args: ('ok',) | Kwargs: {}
ok

Why is it different in those two approaches?为什么这两种方法不同? How does calling _func "bind it" to _func(*args, **kwargs) ?如何调用_func将其“绑定”到_func(*args, **kwargs)

def decorator(func):

Because it is a decorator, we expect it to return something that can be called.因为它是一个装饰器,我们期望它返回一些可以调用的东西。

    return func # don't need to call!

Right, because func is the "something that can be called" which we will return.对,因为func是我们将返回的“可以调用的东西”。 The decorator has no effect.装饰器没有效果。

then if I wrap that in an inner function, it is called liked so然后如果我把它包裹在一个内部 function 中,它被称为喜欢

What we are doing with _func is creating a new function that will be returned by the decorator, and defining its behaviour in terms of the passed-in func .我们对_func的是创建一个的 function 将由装饰器返回,并根据传入的func定义其行为 So we don't call func when the decorator is invoked;所以我们在调用装饰器的时候不调用func but we do call it inside the body of _func , because that's how we make func execute when _func is executed .但是我们确实在_func的主体内调用它,因为这就是我们在执行_func使func执行的方式。

Why is it different in those two approaches?为什么这两种方法不同?

I don't understand the question.我不明白这个问题。 What is the same about them?他们有什么相同之处? They are both defining a decorator, okay.他们都在定义一个装饰器,好吧。 They do it in completely different ways.他们以完全不同的方式做到这一点。

How does calling _func "bind it"如何调用_func “绑定它”

I don't understand what you mean about binding here and _func doesn't get called directly by name in this code.我不明白您在这里绑定的意思,并且_func在此代码中不会直接按名称调用。 It gets called when print_word is called, because the decorator has replaced print_word with a locally created _func .它在调用print_word时被调用,因为装饰器已将print_word替换为本地创建的_func (Every time the decorator is used, a separate function, with the same _func name, is made. Is that what you're stumbling on?) (每次使用装饰器时,都会生成一个单独的 function,具有相同的_func名称。这就是你的绊脚石吗?)

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

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