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.
仅有的幸福2017-05-18 10:57:41
Referred to this problem and solved it.
Nested function gets calling function
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()
过去多啦不再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']