Question

I am trying to extract a particular value from a function which deals with multiple values.

My simplified example:

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

So if I want to use the values of a and b that get created in func() in some other function, how would I extract them?

Was it helpful?

Solution

It's not so much that you need to extract them; you just need to save them somewhere.

If this is a top-level function in a module, consider a module variable:

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

but these look suspiciously related so perhaps they belong in a class?

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

Of course, you could also just make them part of the function's return definition:

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)

OTHER TIPS

One way is to return them:

return (a*x + b*y, a, b)

and you can call your function as:

(result, a, b) = func(x,y)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top