Python:将额外的参数传递给 callable

我有以下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 来计算成本。


守候你守候我
浏览 223回答 1
1回答

烙印99

这在很大程度上取决于value1和的含义value2。我建议添加一个可由 networkx 调用的包装器:def cost_wrapper(i, j, d):    value1 = 0  # set values as needed    value2 = 1    return cost(i, j, d, value1, value2)并将其提供给 networkx:path = nx.dijkstra_path(graph, src, dst, weight=cost_wrapper)或者简单地使它们成为全局变量,而不是参数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python