Python 在具有不同输入参数的函数中调用函数
我对python很陌生,但我没有找到 我有一个河网,我想用一些算法 第一步是加载数据并以我可以使用的方式进行处理。 我需要一个函数来加载和预处理数据,然后调用另一个函数来处理它 根据我想要调用的算法,我需要不同的输入参数。 我需要将算法的参数输入到加载算法中 有没有一种方法可以让函数知道哪个参数是算法的参数 代码知道“calc_网络(数据、算法3、输入B)”的方式符合我的预期 按照我的理解,我需要输入“calc_网络(数据,算法3,0,inputB,0)” 所以我需要为我不需要的值设置空白值,正确吗Python 在具有不同输入参数的函数中调用函数,python,function,qgis,Python,Function,Qgis,我对python很陌生,但我没有找到 我有一个河网,我想用一些算法 第一步是加载数据并以我可以使用的方式进行处理。 我需要一个函数来加载和预处理数据,然后调用另一个函数来处理它 根据我想要调用的算法,我需要不同的输入参数。 我需要将算法的参数输入到加载算法中 有没有一种方法可以让函数知道哪个参数是算法的参数 代码知道“calc_网络(数据、算法3、输入B)”的方式符合我的预期 按照我的理解,我需要输入“calc_网络(数据,算法3,0,inputB,0)” 所以我需要为我不需要的值设置空白值,正
def calc_network(data, algorithm, inputA, inputB, inputC):
def processData(data)
return processedData
def algorithm1(processedData, inputA, inputB)
return results
def algorithm2(processedData, inputA, inputC)
return results
def algorithm3(processedData, inputB)
return results
return results, processedData
我对这个问题的看法是对的还是我有一些基本的误解
提前谢谢
Leo您不会嵌套这样的函数。您将拥有多个函数,并从父函数调用子函数
def functionA(foo):
do stuff
def functionB(foo):
do stuff
def functionC(foo):
do stuff using functionA or functionB
如果你想把你的函数保持在与你所讨论的类似的结构中,你可能想考虑类。
class Foo(object):
def __init__(self, your, data, arguments):
Determine which function to send data to
self.data = call function(s) and get the data.
def algorithm1(self, processedData, inputA, inputB)
return results
def algorithm2(self, processedData, inputA, inputC)
return results
def algorithm3(self, processedData, inputB)
return results
这样,当您需要数据时,可以通过实例化类来实现
foo = Foo(your, data, arguments)
然后,您的结果将可通过以下方式访问:
foo.data
使用
functools尝试此方法。部分:
from functools import partial
def algorithm1(data, input_a, input_b):
return 'algorithm1 result'
def algorithm2(data, input_a, input_c):
return 'algorithm2 result'
def algorithm3(data, input_b):
return 'algorithm3 result'
def calc_network(data, algorithm):
def process_data(data):
return 'processed {}'.format(data)
processed_data = process_data(data)
return algorithm(processed_data), processed_data
print(calc_network('data1', partial(algorithm1, input_a=1, input_b=2)))
print(calc_network('data2', partial(algorithm2, input_a=1, input_c=3)))
print(calc_network('data3', partial(algorithm3, input_b=2)))
这将产生:
('algorithm1 result', 'processed data1')
('algorithm2 result', 'processed data2')
('algorithm3 result', 'processed data3')
为什么要在计算网络中定义所有这些函数?