python - 从函数中获取特定值

标签 python function random return-value extract

我正在尝试从处理多个值的函数中提取特定值。

我的简化示例:

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() 中创建的 ab 值,该怎么办我提取它们?

最佳答案

这并不需要您提取它们;您只需要将它们保存在某个地方即可。

如果这是模块中的顶级函数,请考虑模块变量:

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/

相关文章:

python - lxml xpath 不会忽略 " "

python - 找到最大的差异 - O(n)

c - 是否所有的 C 函数都需要在头文件中声明

c++11 - 需要使用 C++11 的确定性均匀分布

c - 如何在没有 rand() 函数的情况下生成随机数?

sql-server-2008 - 如何从数字列表中选择随机数

python 多处理悲情 - AuthenticationError : digest sent was rejected - Windows

python - swift 将一串字母分成3s

function - PostgreSQL 触发器更新二级相关表

function - 比较haskell中的函数和参数