简体   繁体   中英

How to use variable from a function which inside another function in another function

def func():
    a = 'abc'
    def func2():
        b = 'bcd'
        return b
    return a

def func3():
    c = func()()
    return c

print(func3())

How to use value from variable b from func2 in func3, above is what I have tried, got an error:

Traceback (most recent call last):

  File "<ipython-input-30-cfaa7d1d3a78>", line 12, in <module>
    print(func3())

  File "<ipython-input-30-cfaa7d1d3a78>", line 9, in func3
    c = func()()

TypeError: 'str' object is not callable

Welcome to SO.

  1. As pointed out by the commenters you need to remove the extra () you have after func() .

  2. You never call func2() anywhere.


SIDE NOTE

It's confusing what you're trying to accomplish with this code... ie do you want both a and b available to func3() ? Or just b .


If all you want is to return b so that c=b the code below will accomplish that.

def func():
    a = 'abc'
    def func2():
        b = 'bcd'
        return b
    return func2()

def func3():
    c = func()
    return c

print(func3())

This will yield bcd .


If you want to return a and b so that c=('abc', 'bcd') the code below will accomplish that.

def func():
    a = 'abc'
    def func2():
        b = 'bcd'
        return b
    return a, func2()

def func3():
    c = func()
    return c

print(func3())

This will yield abc , bcd .

I'm not sure if I completely understood what are you asking but it seems like you never call the func2(). Try to add it in the return of func().

def func():
    a = 'abc'
    def func2():
        b = 'bcd'
        return b    
    return a + func2()

def func3():
    c = func()
    return c

print(func3())

Whith this solution my output is:

abcbcd

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