如何在Python中的函数之间共享值? [英] How to share values between functions in Python?
问题描述
我具有以下2个功能:
a = 20
b = 45
def function1():
coin = np.random.randint(0, 100)
a2= a+coin
return a2
def function2():
b2= b+coin
return b2
但是,这里的问题如下:我想使用在 function 2中随机选择的'
. coin
'值(由 function 1
确定)
However, my problem here is as follows: I want to use the randomly selected 'coin
' value (determined in function 1
) inside function 2
.
这里的条件是必须始终在函数1中进行随机选择.最有效的方法是将此 coin
值传递给 function 2
,而不必在 function 2
中调用 function 1
?
The condition here is that the random selection must always be done in function 1. What is the most efficient way to pass this coin
value to function 2
without having to call function 1
inside function 2
?
注意:功能1
应该只返回一个变量,即 a2
.
NOTE: function 1
should only return one variable which is a2
.
推荐答案
编辑后
虽然可以使用全局变量,但我建议使用一个类:
After Edit
While you can use a global variable, I would recommend using a class:
class Functions:
def __init__(self, a, b):
self.a = a
self.b = b
self.coin = 0
def function1(self):
self.coin = np.random.randint(0, 100)
a2 = self.a + self.coin
return a2
def function2(self):
b2 = self.b + self.coin
return b2
f = Functions(a=20, b=45)
f.function1()
f.function2()
两个功能紧密结合.因此,一堂课似乎更适合举行.理想情况下,功能应该是独立的.另一方面,一类的方法应该相互依赖.
Both functions are tightly coupled. Therefore, a class seems more appropriate to hold them. Ideally, functions should be independent. On the other hand, methods of a class are expected to depend on each other.
我建议对函数使用参数.这使它们独立:
I recommend using arguments for your functions. This makes them independent:
def function1(a):
coin = np.random.randint(0, 100)
a2 = a+coin
return a2, coin
def function2(coin):
b2 = b+coin
return b2
a = 20
b = 45
a2, coin = function1(a)
print(function2(coin))
此行:
return a2, coin
返回两个结果".实际上,它构建了一个中间元组.这行:
"returns two results". Actually, it builds an intermediate tuple. And this line:
a2, coin = function1(a)
再次将此元组解压缩为变量.
unpacks this tuple into to variables again.
这篇关于如何在Python中的函数之间共享值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!