Namespace and scope of Python
A variable is a name (identifier) that has a matching object. A namespace is a dictionary that contains variable names (keys) and their corresponding objects (values). An Python expression can access variables in both local and global namespaces. If a local variable and a global variable have the same name, the local variable overrides the global variable. Each function has its own namespace. The scope rules of a method of a class are the same as those of a normal function. Python intelligently guesses whether a variable is local or global, assuming that any variable assigned within a function is local. Therefore, if you want to assign values to global variables within a function, you must use the global statement.
The expression of global VarName tells Python that VarName is a global variable so that Python does not look for this variable in the local namespace.
For example, we define a variable Money in the global namespace. We assign a value to the variable Money within the function, and then Python assumes that Money is a local variable. However, we did not declare a local variable Money before the visit, and the result was a UnboundLocalError error. The following code is shown:
#! / usr/bin/python#-*- coding: UTF-8-*-Money = 1000def Addmoney (): Money = Money + 1print MoneyAddmoney () print Money
Running result:
1000Traceback (most recent call last): File "import.py", line 7, in Addmoney () File "import.py", line 5, in Addmoney Money = Money + 1UnboundLocalError: local variable 'Money' referenced before assignment
If you want to declare that the variable Money is a global variable, declare it with global. The specific implementation code is as follows:
#! / usr/bin/python#-*- coding: UTF-8-*-Money = 1000def Addmoney (): global Money Money = Money + 1print MoneyAddmoney () print Money
Running result
10001001