Look at the following code first, obviously not work. Because the code tries to reference a variable A that is not defined in Testvariablescope (), you must make an error, such as-1.
But if you comment out the 2nd line of code. The code can run through,-2.
The question comes: Testvariablescope.a is not also not defined, why can work? The explanation is as follows: First look at line 8th of the code, TESTVARIABLESCOPE.A is defined in the SetVariable method, and SetVariable () is called before Testvariablescope (). So Testvariablescope () TESTVARIABLESCOPE.A has been defined at the time of the call.
The problem is: line 7th of the code, A is also defined. Why Testvariablescope () in reference A is an error. The difference is that a is only a local variable in setvariable (), Testvariablescope of course cannot refer to local variables defined in SetVariable. Because it violates the LEGB principle. Testvariablescope.a is not the same, he is a global variable OH. So testvariablescope can certainly access this global variable without violating the LEGB principle at all.
The question is three: Why TESTVARIABLESCOPE.A is a global variable, and a is not. Because the function in Python is both an object and a global object. Testvariablescope.a is actually a variable testvariablescope the global object, which is also the global variable. See figure-3
1 deftestvariablescope ():2 Print(a)3 Print(TESTVARIABLESCOPE.A)4Testvariablescope.a=135 6 defsetvariable ():7A=128Testvariablescope.a=129 Ten if __name__=='Demo': One Print('Demo is running') A - if __name__=='__main__': - setvariable () the Testvariablescope () -b=Testvariablescope -B ()
Figure-1
Figure-2
Figure-3
Creating global variables from a function object in Python