我编写了一个程序 (A),它采用我在单独程序 (B) 中编写的函数名称作为输入。我想在程序 (A) 中使用这些函数,因此我尝试通过执行以下操作来运行 (A):A(f1, f2, f3, f4)
在 (A) 的顶部,我使用 import B 导入了程序 (B)。在 (A) 中只有一个函数(不包括 main)接受四个输入(f1、f2、f3、f4),然后使用它们,如下所示:
for i in range(x, y):
z = B.f1(i)
u = B.f2(i)
...
...
问题是,当我尝试运行 A(f1, f2, f3, f4) 时,出现错误
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
A(f1, f2, f3, f4)
NameError: name 'f1' is not defined
我发现 python 无法将 (B) 中的函数识别为 (A) 中的输入,但我不知道为什么或如何连接这两个程序。
更新:程序A
def A(f1, f2, f3, f4) :
x = 0
y = 10
for i in range(x, y):
x = B.f1(i) //returns float
plt.plot(i, x)
...
最佳答案
根据对问题的字面解读,如果您通过导入 B
import B
那么对 B 中定义的函数、变量、类等的每个引用都必须以 B.func1
等形式完成。
您的错误消息清楚地表明您正在尝试执行A(f1, f2, f3, f4)
。这应该是 A(B.f1, B.f2, B.f3, B.f4)
编辑从您更新的问题来看,我猜您想要类似的东西:
import B
def A(input_function1, input_function2, input_function3, input_function4) :
x = 0
y = 10
for i in range(x, y): #btw, you don't need the x value here if it's 0
x = input_function1(i) //returns float #I removed the 'B.'
plt.plot(i, x)
# Other stuff here
if __name__=='__main__':
A(B.f1, B.f2, B.f3, B.f4)
# or alternatively A(B.f78, B.f21, B.f1, B.f90) or whatever
或者:
from B import f1, f2, f3, f4
def A(f1, f2, f3, f4) :
# Stuff here
if __name__=='__main__':
A(f1, f2, f3, f4) # Explicit imports mean that the 'B.' prefix is unnecessary
关于python - 使用函数作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132950/