英文:
Iterate over list of objects, which can be tuples or objects
问题
我有一系列的函数,它们都接受一个数字,对其进行操作,然后返回变换后的数字,其中一些接受额外的参数,而另一些则不接受。
我需要创建一个包含这些函数及其参数的对象,然后在不同的类中将它们全部应用于我的数字,有点类似于管道。
我可以使用`functools.partial`,如下所示:
```python
from functools import partial
ApplyFuncs().apply_funcs(num=5,
funcs=[
foo,
partial(bar, arg1=5)
])
但这需要潜在用户知道如何使用partial
。
我考虑提交一个元组(函数,参数字典),如下所示:
ApplyFuncs().apply_funcs(num=5,
funcs=[
foo,
(bar, args=dict(arg1=5))
])
但如果函数不需要额外的参数,我应该提交什么呢?如果不提交任何东西,我将无法迭代列表,因为有些对象有2个元素(元组),而有些只有1个(单个对象)。
我可以编写更复杂的逻辑来解开这些对象,将它们分类为元组或单个对象,然后根据情况应用,但这似乎有点繁琐。
你知道是否有更简单、更Pythonic的方法吗?
<details>
<summary>英文:</summary>
I have a list of functions that all take a number, do something to it and then return transformed number, some of them accept extra arguments, some not.
def foo(num):
return num + 5
def bar(num, arg1: int):
return num + 5 + arg1
class ApplyFuncs:
def apply_funcs(self, num, funcs):
for func in funcs:
num = func(num)
return num
I need to make an object of these functions and their arguments and apply them all to my number in a different class, sort of like a pipeline.
I can either use `functools.partial` like so:
from functools import partial
ApplyFuncs().apply_funcs(num=5,
funcs=[
foo,
partial(bar, arg1=5)
])
but that requires for potential user to know to use partial.
I was thinking of submitting a tuple (func, dict of args) like so:
ApplyFuncs().apply_funcs(num=5,
funcs=[
foo,
(bar, args=dict(arg1=5))
])
but then what do I submit when the func requires no extra args? If I don't, I'm unable to iterate over the list as some objects have 2 elements (tuples) and some 1 (single object).
I would be able to write a more complex logic that unwraps the objects, categorizes them into either tuples or single objects, and then applies based on that, but that seems to be overkill.
Do you know if there's an easier, more pythonic way?
</details>
# 答案1
**得分**: 1
我相当优雅地解决了它(在我看来)。我可能会使用这个。
```python
def apply_funcs(num)
for obj in self.function_list:
if callable(obj):
num = obj(num)
else:
num = obj[0](num, **obj[1])
return num
英文:
Well, I solved it quite elegantly (imo). I will probably use this.
def apply_funcs(num)
for obj in self.function_list:
if callable(obj):
num = obj(num)
else:
num = obj[0](num, **obj[1])
return num
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论