我正在尝试从处理多个值的函数中提取特定值。
我的简化示例:
def func(x, y):
a = ran(0,10) #creates random integer
b = ran(0,10)
return a*x + b*y
print a*x + b*y
因此,如果我想在其他函数中使用在 func()
中创建的 a
和 b
值,该怎么办我提取它们?
最佳答案
这并不需要您提取它们;您只需要将它们保存在某个地方即可。
如果这是模块中的顶级函数,请考虑模块变量:
import random
rand1 = random.randint(0, 10)
rand2 = random.randint(0, 10)
def f(x, y):
result = rand1*x + rand2*y
print result
return result
但是这些看起来可疑相关,所以也许它们属于一个类?
class YourClass(object):
def __init__(self):
self.rand1 = random.randint(0, 10)
self.rand2 = random.randint(0, 10)
def your_func_as_a_method(self, x, y):
result = self.rand1*x + self.rand2*y
print result
return result
当然,您也可以将它们作为函数返回定义的一部分:
def f(x, y):
rand1 = random.randint(0, 10)
rand2 = random.randint(0, 10)
result = rand1*x + rand2*y
print result
return (result, rand1, rand2)
fxy, a, b = f(x, y)
关于python - 从函数中获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700625/