我得到了Python装饰器的基本原理,我喜欢语法。但是,他们似乎对你能做的事情有点限制。
有一种优雅的方法可以将多个函数作为参数处理,如下所示吗?
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()
我可以在哪里放下child_fn2代码?我尝试过的一些想法似乎剥夺了装饰者的简洁和优雅。
答案 0 :(得分:2)
你可以这样做:
public class EmailSender : IEmailSender
{
private EmailOptions _emailOptions;
public EmailSender(EmailOptions options) => _emailOptions = options;
但它可能不适合装饰者。从概念上讲,装饰器应该改变他们装饰的单个功能的功能;在平等的基础上对另外两个函数进行排序的函数作为装饰者可能没什么意义。例如,装饰器创建的新函数现在名为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')
,替换原始func2
。这只对某些特定用例有意义,而避免使用装饰器语法会给你更大的灵活性。
不使用装饰器语法更有意义:
func2