将带有不同参数的函数传递给另一个函数时,如何避免过度使用 **kwargs?
我有一个像这样的函数:
def outer_function(input1, input2, func):
a = ....[calculations that depend on input1 and input2]....
b = ....[calculations that depend on input1 and input2]....
c = ....[calculations that depend on input1 and input2]....
d = func(a=a, b=b, c=c)
return d
我可以将 func1
或 func2
作为参数 func
传递到outer_function中。问题是 func1
实际上只依赖于 a
和 b
,因此可以写成这样
def func1(**kwargs):
a = kwargs.get('a')
b = kwargs.get('b')
return something_with_a_and_b
同时,func2 取决于所有 3 个值,例如所以:
def func2(**kwargs):
a = kwargs.get('a')
b = kwargs.get('b')
c = kwargs.get('c')
return something_with_a_and_b_and_c
这可行,但我不喜欢它,因为它要求我将很多东西(在我的实际情况下)作为参数传递给 outer_function
中的 func
实际例程并不总是使用它,所以它模糊了我的例程实际依赖的内容(相反,您必须查看我从 **kwargs 访问的值。是否有更好的方法来处理这种类型的情况?我有一个更清晰的类实现,但我需要在这种特定情况下的功能方法。
I have a function like so:
def outer_function(input1, input2, func):
a = ....[calculations that depend on input1 and input2]....
b = ....[calculations that depend on input1 and input2]....
c = ....[calculations that depend on input1 and input2]....
d = func(a=a, b=b, c=c)
return d
where I can pass either func1
or func2
into the outer_function as the argument func
. The problem is that func1
actually only depends on a
and b
, and so can be written like
def func1(**kwargs):
a = kwargs.get('a')
b = kwargs.get('b')
return something_with_a_and_b
Meanwhile, func2 depends on all 3 values, like so:
def func2(**kwargs):
a = kwargs.get('a')
b = kwargs.get('b')
c = kwargs.get('c')
return something_with_a_and_b_and_c
This works, but I don't like it because it requires me to pass a lot of stuff (in my actual case) as arguments to func
within outer_function
that aren't always used by the actual routine, and so it obscures what my routines actually depend upon (and instead you have to look at what values I'm accessing from **kwargs. Is there a better way to handle this type of situation? I have a cleaner implementation as a class, but I need a functional approach in this specific situation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种更清洁的方式,这是使装饰器处理自定义功能组成的方法。没有唯一的解决方案,因为它在组成顺序上逐渐消失。在这里示例
输出
A cleaner way to habdle this is make decorators to handle custom composition of functions. There is not a unique solution since it depdens on the order of composition. Here an example
Output