假設有這樣一段程式碼:
def demo():
a = 1
b = 0
c = a / b
def main():
try:
demo()
except Exception as e:
print(e)
main()
現在希望在異常時不對demo函數內的程式碼做任何修改也可以獲得demo中a和b的值。
PHP中文网2017-05-18 10:57:41
用全域變數 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
函數外加引用, 這是變數作用域的知識
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
或把a,b放一個字典變數裡, 這樣就不需要global了
g = {"a":0,"b":0}
def demo():
g['a'] = 1;
g['b'] = 0
c = g['a'] / g['b']