Changes to the value of global variables in Python

Source: Internet
Author: User
Python's Global variables: int string, list, dic (map) can modify its value if there is a global. Regardless of whether this global exists in the IF, or whether the if can be executed.

However, if there is no

If BGlobal:     global g_strval;

int string will be an error. The list dic (map) is OK.

#!/usr/bin/dev python import sys import OS g_nval = 0;  G_strval = "AAAA"; G_map = {"AAA": "111", "BBB": "222", "CCC": "333", "ddd": "444"} G_ls = [' A ', ' B ', ' C '] def fixint (bglobal = False          ): if Bglobal:global g_nval;    G_nval = G_nval + 1;      def fixstring (BGlobal = False): if Bglobal:global g_strval;  #fix String Value G_strval = g_strval + ' B ';      def fixmap (BGlobal = False): if Bglobal:global g_map;   #fix map Value g_map[' aaa '] = ' aaa__ ' + g_strval;   g_map[' bbb '] = ' bbb__ ' + g_strval;   g_map[' CCC '] = ' ccc__ ' + g_strval;    g_map[' ddd '] = ' ddd__ ' + g_strval;        def fixlist (BGlobal = False): if Bglobal:global G_ls;        G_ls.append (' 1 ');        def printval (strinfo): if strinfo:print ("= = =%s ====="%strinfo);   Print ("int value:%d"%g_nval);   Print ("string value:%s"%g_strval);   Print ("Map value:%s"%g_map);   Print ("list value:%s"%g_ls);    Print ("\ n"); If "__main__" = = __name__: Printval ("The Orgin Vlaue ");   Fixint ();   Fixstring ();   Fixmap ();      Fixlist ();      Printval ("Print all BGlobal = False Vlaue");   Fixint (True);   Fixstring (True);   Fixmap (True);      Fixlist (True); Printval ("Print all BGlobal = True Vlaue");

Results:

= = The Orgin vlaue =====int value:0string value:aaaamap value:{' aaa ': ' 111 ', ' BBB ': ' 222 ', ' CCC ': ' 333 ', ' ddd ': ' 444 '}li  St value:[' A ', ' B ', ' C ']g_nval src:0g_nval dst:1==== print all BGlobal = False value =====int value:1string value:aaaabmap value:{' aaa ': ' Aaa__aaaab ', ' BBB ': ' Bbb__aaaab ', ' CCC ': ' Ccc__aaaab ', ' ddd ': ' Ddd__aaaab '}list value:[' A ', ' B ', ' C ', ' 1 '] G_nval src:1g_nval dst:2==== Print all BGlobal = True value =====int value:2string value:aaaabbmap value:{' aaa ': ' AAA__AAA ABB ', ' BBB ': ' Bbb__aaaabb ', ' CCC ': ' Ccc__aaaabb ', ' ddd ': ' Ddd__aaaabb '}list value:[' A ', ' B ', ' C ', ' 1 ', ' 1 ']

Why modify global Dict variables without the global keyword
For example, the following code

s = ' Foo ' d = {' A ': 1} def f ():   s = ' bar '   d[' b '] = 2 f () print S print D

Why would I change the value of dictionary d without first declaring it with the global keyword?
This is because,
In s = ' bar ', it is "ambiguous" because it can either represent a reference to the global variable s or create a new local variable, so in Python, the default behavior is to create a local variable unless you explicitly declare global.
In the d[' B ']=2, it is "explicit" because if D is considered a local variable, it will report keyerror, so it can only refer to global D, so it does not need to explicitly declare global by superfluous.
The above two sentence assignment statement is actually different behavior, one is rebinding, one is mutation.

But if it's the following,

D = {' A ': 1} def f ():   d = {}   d[' b '] = 2 f () print D

In d = {}, it is "ambiguous", so it is creating a local variable D instead of referencing global variable D, so d[' B ']=2 is also the local variable of the operation.

Pushed away, the essence of all this is "whether it is clear".
If you think about it, you will find that not only dict does not need global, all "clear" things do not need global. Because of the type of type STR, there is only one modification method, that is, x = y, which is exactly the method of creating the variable, so there is ambiguity, and I do not know whether to modify or create it. and dict/list/objects, etc., can be modified by dict[' x ']=y or List.append (), and do not conflict with the creation of variables, do not produce ambiguity, so do not have explicit global.


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.