简体   繁体   中英

Can I use python return function to only return the value to the specific function

If I have this

def fun1:
    a = 2
    b = 3
    return a
    return b     #problem is here
def fun2:
    c = fun1()
print(fun1())

I want to return a be a default return and fun1 return a to every other functions but return b only works for returning to fun2 and nowhere else

What you can do is create an optional parameter for the function which decides what value to return.

def fun1(arg=0):
    a = 2
    if arg != 0:
        a = 3
    return a
def fun2():
    c = fun1(1)
print(fun1())
fun2()

Here if you call fun1() without any arguments, it will return you 2. But if you give it any integer argument [ example: fun1(2) or fun1(1) ], it will return you 3.

Whenever return a is executed - it EXITS the function fun1 .

So the line return b will NEVER be executed.

You can do something like:

def fun1(return_b=False):
    a = 2
    b = 3
    if return_b:
        return b
    else:
        return a

def fun2:
    c = fun1(return_b=True)

Read more about Default Argument Values here .

If you want to return both a and b , you can return a tuple of them: return a, b

A function can only return one output at a time. Meaning if you have more than one return statements in the quesiton, only the first one would be executed and any line written after that statement won't be executed.

In your example you typed return a before return b meaning the function would only return the value of a and the return b line won't be executed.

From your comment on your own question I can see that you want to print a first and then want the value of c to be 3. For that you can do this -

def fun1():
    a = 2
    b = 3
    print(a)
    return b

def fun2():
    c = fun1()

fun1()

You just need two different functions.

Everyone just calls fun1() , but only fun2() calls fun1a() :

def fun1():
    a = 2
    b = 3
    return a

def fun1a():
    a = 2
    b = 3
    return b 

def fun2():
    c = fun1a()
    return c
print(fun1())
print(fun2())

Here is only an answer to your strange idea: first, get the current frame through inspect.currentframe , and then get the frame called by the previous layer through the current frame and inspect.getframeinfo . The function name will be recorded in the returned value, and different values can be returned by comparing the function name.

import inspect


def fun1():
    a = 2
    b = 3
    curr_frame = inspect.currentframe()
    back_frameinfo = inspect.getframeinfo(curr_frame.f_back)
    return b if back_frameinfo.function == 'fun2' else a


def fun2():
    return fun1()


print(fun1(), fun2())    # 2 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM