我有一个 function_1 ,如下所示:
def my_func_1():
a = 2
b = 3
r1 = a+b
r2 = a*b
return r1, r2
我想在另一个函数_2 中调用这个函数_1。问题是我可以在 function_2 中调用 function_1 返回值:
import my_func_1 *
def my_func_2():
result_1 = my_func_1()[0]
result_2 = my_func_1()[1]
问题是
my_func_1()
计算量相当大。我应该能够调用 function_1 一次,同时将不同的返回值分配给 function_2 中的不同变量。我该怎么办呢。预先感谢您的帮助。
啊啊,这太简单了,我明白了:
import my_func_1 *
def my_func_2():
result = my_func_1()
result_1 = result[0]
result_2 = result[1]
不要返回 r1 和 r2,而是在 my_func_1() 中将 r1 和 r2 声明为全局变量。不仅仅是r1和r2,如果你还想声明my_func_1()执行的更多变量,你可以声明。让 my_func_1() 不返回任何内容。执行 my_func_1()。然后在 my_func_2() 中使用 r1 和 r2。
def my_func_1():
global r1
global r2
a = 2
b = 3
r1 = a+b
r2 = a*b
#do not return any value
'''
this step is important since global variables r1 & r2 can be used by
other functions only if my_func_1() is executed
'''
my_func_1()
def my_func_2():
#Do whatever you want to do with r1 & r2
result_1 = r1
result_2 = r2