假设我有一系列函数调用。
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 ..
我能够通过SCIPY
quad
(数字积分)将args从一个函数传递到另一个函数,以确保args不可变。我还可以通过可变参数的SCIPY minimize
(优化)将args从一个函数传递给另一个函数。我的麻烦是将非可变输入pick
从一个函数传递给另一个函数。如果在上面的简化示例中将print(pick)
放置为每个已定义函数的第一行,并且如果我将此函数链称为callme = func3( 2 , func2(pick = pick, args) , [6, 0.5] )
然后我的代码最终会吐出一条错误消息,内容为
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
但首先它会执行以下操作:
1
2
1
2
2 # (from pick = 2 in func3)
[6 0.5]
这是怎么/为什么发生的,并且可以通过一系列函数调用将输入的
pick
从一个函数发送到另一个函数吗?编辑:我的猜测是将pick作为类的对象传递,或使用kwargs,或将pick作为由单个元素组成的不可包装的元组传递;但我不确定这是否正确或如何实现。理想情况下,我不知道有一些操作像
callme = func3( pick.func2 , func2, [6, 0.5] )
一样简单。我尝试将pick
声明为global
,但这会导致有关全局参数的错误消息。
最佳答案
我从每个函数中删除了pick
作为输入,但将其保留为functino中的变量。然后,将以下代码放在函数链之前,以初始化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
在功能链之后,使用重新初始化的
pick
运行功能链。由于不再是从函数链顶部向下传递的参数,因此错误源已消失。
关于python-3.x - 我试图将一个非可变整数参数从一个函数传递给其他定义的函数;我怎么了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42898612/