[英]Python - Passing arguments back and forth between functions
假设我有一些参数传递给函数,我用这些参数进行一些计算,然后将结果传递给另一个函数,在此进一步使用它们。 我将如何将结果传递回第一个函数,并跳到一个点,这样就不会将数据发送回第二个函数,从而避免陷入循环。
这两个函数位于两个不同的python脚本中。
我目前正在这样做的方法是,将所有可能来自第二个脚本的新参数添加为非关键字参数,并将所有参数从第一个函数传递给第二个函数,即使第二个函数中不需要它们也是如此。 第二个函数将所有参数传递回第一个,非关键字参数上的if
条件用来检查其是否具有默认值,以确定第二个函数是否已将数据发送回去。 在f1.py中:
def calc1(a, b, c, d = []):
a = a+b
c = a*c
import f2
f2.calc2(a, b, c)
If d != []: # This checks whether data has been sent by the second argument, in which case d will not have its default value
print(b, d) # This should print the results from f2, so 'b' should
# retain its value from calc1.
return
在另一个脚本(f2.py)中
def calc2(a, b, c):
d = a + c
import f1
f1.calc1(a, b, c, d) # So even though 'b' wasn't used it is there in
# f2 to be sent back to calc1
return
递归调用两个方法通常是一个坏主意。 在两个文件之间尤其糟糕。 看起来您想调用calc1()
,让它在内部调用calc2()
,然后根据calc2()
的结果来决定要做什么。
这是您要做什么?
#### f1.py
import f2
def calc1(a, b, c):
a = a+b
c = a*c
d = f2.calc2(a, b, c)
# This checks whether data has been sent by the second argument,
# in which case d will not have its default value
if d:
# This should print the results from f2, so 'b' should retain
# its value from calc1.
print(b, d)
#### f2.py
def calc2(a, b, c):
return a + c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.