简体   繁体   English

Python装饰器可以将多个函数用作参数?

[英]Python decorator for multiple functions as arguments?

I get the basic principle of Python decorators and I like the syntax. 我了解了Python装饰器的基本原理,并且喜欢语法。 However, they seem a little limited on what you can do. 但是,他们似乎对您的工作有所限制。

Is there an elegant way to go about handling multiple functions as arguments like below? 是否有一种优雅的方式可以将多个函数作为如下参数处理?

def parent_fn(child_fn1, child_fn2):
    def wrapper():
        print('stuff is happening here')
        child_fn1()
        print('other stuff is happening here')
        child_fn2()
    return wrapper

@parent_fn
def decorated():
    print('child_fn1 stuff here')

decorated()

Where could I put the child_fn2 code? 我可以在哪里放置child_fn2代码? The few ideas I have tried appears to take away from the simplicity and elegance of the decorator. 我尝试过的一些想法似乎摆脱了装饰器的简单和优雅。

You could do that: 您可以这样做:

import functools

def sequence_with(f):
    def wrap(g):
        @functools.wraps(g)
        def sequenced_func():
            f()
            g()
        return sequenced_func
    return wrap

def func1():
    print('func1')

@sequence_with(func1)
def func2():
    print('func2')

but it's probably not a good conceptual fit for decorators. 但是对于装饰师来说,这可能不是一个很好的概念选择。 Conceptually, decorators are supposed to alter the functionality of a single function they decorate; 从概念上讲,装饰器应该更改其装饰的单个功能的功能。 a function that sequences two other functions on an equal footing may not make much sense as a decorator. 一个在相等位置上对其他两个函数进行排序的函数作为装饰器可能没有多大意义。 For example, the new function created by the decorator is now under the name func2 , replacing the original func2 . 例如,装饰器创建的新功能现在以名称func2代替了原来的func2 That only makes sense for some specific use cases, whereas avoiding decorator syntax would give you more flexibility. 这仅对某些特定用例有意义,而避免使用装饰器语法将为您提供更大的灵活性。

It makes more sense to not use decorator syntax: 不使用装饰器语法更有意义:

def sequence(f, g):
   def sequenced_func():
       f()
       g()
   return sequenced_func

def func1():
    print('func1')

def func2():
    print('func2')

sequenced_func = sequence(func1, func2)

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

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