python - How to get value in nested function
PHP中文网
PHP中文网 2017-05-18 10:55:41
0
3
727

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中文网

认证0级讲师

reply all(3)
仅有的幸福

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

Ty80

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()
过去多啦不再A梦

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']
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!