Creating global variables from a function object in Python

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.