Python in Locals () and Globals ()

Source: Internet
Author: User

1, locals () and Globals () are Python's built-in functions that provide a dictionary of ways to access local variables and global variables.

Example code:

1 defTest (ARG):2A=13b=24Data_dict = {}5     Printlocals ()6     PrintGlobals ()7 8 9 if __name__=='__main__':TenTest (3)

The output is:

1{'a': 1,'data_dict': {},'b': 2,'Arg': 3}2{'__builtins__': <module'__builtin__'(built-inch);'__file__':'f:/work/workspace/pythonworkspace/learn/locals_globals.py','__package__': None,'Test': <function test at 0x0239f830>'__name__':'__main__','__doc__': None}
2, locals () return is a deep copy of the current local variable, modify the value of the variable in locals (), in fact, there is no effect on the original variable itself. and Globals () returns a dictionary of global variables, modifies the contents, and the value is really changed.

Example code:

1b = 5#define a global variable2 deftest2 ():3A=14Locals () ["a"] = 2#modifying local variables5     Print "a=", a6Globals () ["b"] = 6#Modifying global variables7     Print "b=", b8 9 if __name__=='__main__':TenTest2 ()

The output is:

A= 1B= 6

Python in Locals () and Globals ()

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.