[Level 3] How to implement reflection in Python.

The Python Code:
#!/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

Popular posts from this blog

[Level 1] Reversion of git

[Level 2] iif in Python