问题
Suppose I have a chain of function calls.
def func1( pick, arg1, arg2 ):
if pick == 1:
do stuff with arg1 and arg2
elif pick == 2:
do other stuff with arg1 and arg2
return stuff that got done
def func2( pick, arg1, arg2, arg3 ):
if pick == 1:
do stuff with arg1 and arg2 and arg3
elif pick == 2:
do other stuff with arg1 and arg2 and arg3
return stuff that got done
def func3( pick, func2, arg3 ):
if pick == 1:
do stuff with funcs and arg3
elif pick == 2:
do other stuff with funcs and arg3
return stuff that done
etc ..
I was able to pass args from one function to another via SCIPY quad
(numerical integration) so as to ensure that the args were not mutable. I was also able to pass args from one function to another via SCIPY minimize
(optimization) in which the args are mutable. My trouble is in passing the non-mutable input pick
from one function to another. If I were to place print(pick)
as the first line of each defined function in the simplified example above, and if I were to call this chain of functions as
callme = func3( 2 , func2(pick = pick, args) , [6, 0.5] )
then my code would eventually spit out an error message that reads
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
but first it would do something like:
1
2
1
2
2 # (from pick = 2 in func3)
[6 0.5]
How/Why is this happening, and is it possible to send the input pick
from one function to another in a chain of function calls?
Edit: My guess would be passing pick as an object of a class, or using kwargs, or passing pick as an unpackable tuple consisting of a single element; but I'm not sure if this is correct or how to implement this. Ideally, there is some operation I'm unaware of that is as simple as callme = func3( pick.func2 , func2, [6, 0.5] )
. I've tried declaring pick
as global
, but this results in an error-message about a parameter being global.
回答1:
I removed pick
as an input from every function but left it as a variable in the functino. I then placed the following code before the function chain to initialize pick
.
def selectdist(pick):
## 1 for original representation
## 2 for normal representation on semilog(x) axis
## 3 for normal representation on linearly-spaced ln(x) axis
return int(pick)
pickdist = selectdist(3) # choose 1 2 or 3
After the function chain, one run the function chain using a re-initialized pick
. Since it no longer is an argument that is passed from the top of the function chain on down, the source of the bug is gone.
来源:https://stackoverflow.com/questions/42898612/i-am-trying-to-pass-a-non-mutable-integer-argument-from-one-function-to-other-de