search

Home  >  Q&A  >  body text

python - How to get value in nested function

Suppose there is such a piece of code:

def demo():
    a = 1
    b = 0
    c = a / b

def main():
        try:
            demo()
        except Exception as e:
            print(e)
main()

Now we hope that the values ​​of a and b in the demo can be obtained without making any modifications to the code in the demo function when an exception occurs.

PHP中文网PHP中文网2755 days ago773

reply all(3)I'll reply

  • 仅有的幸福

    仅有的幸福2017-05-18 10:57:41

    Referred to this problem and solved it.
    Nested function gets calling function

    reply
    0
  • PHP中文网

    PHP中文网2017-05-18 10:57:41

    Can be achieved using global variables global

    a = b = 0
    def demo():
        global a, b
        a = 1
        b = 0
        c = a / b
    
    def main():
            try:
                demo()
            except Exception as e:
                print 'a: %d, b: %d' % (a, b)
                print(e)
    main()

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-18 10:57:41

    Function plus reference, this is the knowledge of variable scope

    a = None
    b = None
    def demo():
        global a, b
        a = 1
        b = 0
        c = a / b
    
    def main():
        try:
            demo()
        except Exception as e:
            print(e)
    main()
    
    print a
    print b

    Or put a and b in a dictionary variable, so that global is not needed

    g = {"a":0,"b":0}
    def demo():
        g['a'] = 1;
        g['b'] = 0
        c = g['a'] / g['b']

    reply
    0
  • Cancelreply