Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

function - Python: Pass extra arguments to callable

I have the following python code:

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)

Now I want to pass two values value1 and value2 to the cost function.

The networkx documentation says the weight can be a callable that accepts exactly 3 arguments. But i need value1 and value2 for calculations. How can this be done?

Edit The solution using functools works well. However, my function is in a class as follows:

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)

Using this approach, nx.dijkstra_path insists upon assigning src to self. Thus the interpreter complains that self is assigned multiple values. I need self for calculating the cost.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need a function that wraps cost. A quick way is to use functools.partial.

import functools

def cost(i, j, d, value1, value2):
    'Example function'
    return i, j, d, value1, value2

# This makes a new function which takes all parameters of `cost` except those 
# you've already passed. Here I'm going to set value1 and value2 to 1 and 2 
# respectively.
cost_partial = functools.partial(cost, value1=1, value2=2)

# A new function that only accepts the 3 args i, j, d
cost_partial('i', 'j', 'd')  # --> ('i', 'j', 'd', 1, 2)

# use as
path = nx.dijkstra_path(graph, src, dst, weight=cost_partial)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...