简体   繁体   English

如何使用实例方法作为装饰器?

[英]How can one use an instance method as decorator?

How the following code works, without passing the function (func) to the object method task().以下代码如何工作,而不将函数 (func) 传递给对象方法 task()。

class Pipeline:
    def __init__(self):
        self.tasks = list()
        
    def task(self):
        def inner(func):
            self.tasks.append(func)
            return func
        return inner

pipeline = Pipeline()
    
@pipeline.task()
def first_task(x):
    return x + 1

print(pipeline.tasks)

For example, comparing it to the following.例如,将其与以下内容进行比较。 Adding additional functionality to a given function.向给定函数添加附加功能。 I just can't figure out in the above example how the func is getting passed to task() method.在上面的示例中,我无法弄清楚 func 是如何传递给 task() 方法的。

def logger(func):
    def inner(*args):
        print('Calling function: {}'.format(func.__name__))
        print('With args: {}'.format(args))
        return func(*args)
    return inner

@logger
def add(a, b):
    return a + b

Here:这里:

@pipeline.task()
def first_task(x):
    return x + 1

pipeline.task() calls the task method of pipeline . pipeline.task()调用task的方法pipeline This returns the function inner .这将返回函数inner

The @ indicates that this function ( inner ) is to be used as a decorator. @表示这个函数( inner )将用作装饰器。 So inner is called and the subsequent function definition def first_task... is passed as its argument, func .因此调用了inner ,随后的函数定义def first_task...作为其参数func传递。

inner adds the function func to the pipeline's list of tasks. inner将函数func添加到管道的任务列表中。

You can read it as something like:你可以把它读成这样:

inner = pipeline.task()
# inner is a function created by pipeline.task()
#  to add a function to the pipeline's task list
@inner
def first_task(x):
    return x + 1

And decorator syntax makes this behave similarly to:装饰器语法使其行为类似于:

inner = pipeline.task()
def first_task(x):
    return x + 1
first_task = inner(first_task)

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

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