我有以下的Python代码:
import networkx as nx
def cost(i, j, d, value1, value2):
# some operation involving all these values
return cost
# graph is a networkx graph
# src, dst are integers
# cost is a callable that is passed 3 values automatically i.e. src, dst and d
# d is a dictionary of edge weights
path = nx.dijkstra_path(graph, src, dst, weight=cost)
现在我想将两个值
value1
和value2
传递给cost
函数。
networkx
文档表示weight
可以是一个接受3个参数的可调用函数。但我需要value1
和value2
进行计算。如何做到这一点?
编辑
使用functools的解决方案很好。但是,我的函数在一个类中,如下所示:import networkx as nx
import functools
class Myclass:
def cost(self, i, j, d, value2):
# some operation involving all these values
# also need self
# graph is a networkx graph
# src, dst are integers
# cost is a callable that is passed 3 values automatically i.e. src, dst and d
# d is a dictionary of edge weights
# path = nx.dijkstra_path(graph, src, dst, cost)
cost_partial = functools.partial(cost, self=self, value2=5)
path = nx.dijkstra_path(graph, src, dst, cost_partial)
使用这种方法,nx.dijkstra_path
一定会将src
分配给self
。因此解释器会抱怨self
被分配了多个值。
我需要self
来计算成本。