[Level 3] How to implement reflection in Python.
The Python Code:
The output is:
As you can see,
The f1() function cannot modify global variable "a" successfully,
we can say that, exec is a fact function, and unless you declare a variable as a global variable,
or you just deal with a local variable. Like f1()
So if you want to deal with global variable,
please remember to declare it as the global variable first. Like f2()
Wish this helps. regards, Stanley Huang
#!/bin/env python def f1(): exec 'a=1' def f2(): exec 'global a; a=2' def f3(): print a global a a=0 f1() f3() f2() f3()
The output is:
# /tmp/t.py 0 2
As you can see,
The f1() function cannot modify global variable "a" successfully,
we can say that, exec is a fact function, and unless you declare a variable as a global variable,
or you just deal with a local variable. Like f1()
So if you want to deal with global variable,
please remember to declare it as the global variable first. Like f2()
Wish this helps. regards, Stanley Huang
Comments
Post a Comment