Python - 在函数之间来回传递参数

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