[英]Which pattern should I use to call different functions in the same loops?
I often use the same set of nested functions inside which I call different functions.我经常使用同一组嵌套函数,在其中调用不同的函数。 Something with analogous structure to this:
与此结构类似的东西:
data = 'example'
...
for i in range(10):
# use data here
another_data='another'
for j in range(10):
some_func(i, j, data)
...
for i in range(10):
# use data here
another_data='another'
for j in range(10):
another_func(i, j, another_data)
Which pattern should I use to avoid coping the code?我应该使用哪种模式来避免处理代码?
I tried with decorator, but I didn't know how to pass arguments to some_func
that were created in inside wrapper function and omit passing arguments them when calling some_func
.我尝试使用装饰器,但我不知道如何将 arguments 传递给在内部包装器 function 中创建的
some_func
并在调用some_func
时省略传递 arguments 它们。
You can pass a function as parameter.您可以将 function 作为参数传递。 No need for a special design pattern.
不需要特殊的设计模式。
def some_func(i, j, data):
pass
def another_func(i, j, data):
pass
def process_data(data, processor_function):
for i in range(10):
# use data here
another_data='another'
for j in range(10):
processor_func(i, j, data)
data = 'example'
process_data(data, some_func)
process_data(data, another_func)
You can loop through a list of functions:您可以遍历函数列表:
funcs = [some_func, another_func]
data = 'example'
for i in range(10):
for j in range(10):
for func in funcs:
func(i, j, data)
I have finally used a generator:我终于使用了一个生成器:
def some_func(i, j, data):
pass
def another_func(i, j, data):
pass
def input_generator(data):
for i in range(10):
# use data here
another_data='another'
for j in range(10):
yield i, j, data
data = 'example'
for i, j, data2 in input_generator(data):
some_func(i, j, data2)
another_func(i, j, data2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.