In this article, let’s take a look at the namespace and scope of the python programming language. In this article we will take a look at python namespaces, and namespaces and scopes. Learn something about them.
Namespace and scope:
A variable is the name (identifier) that holds the matching object. A namespace is a dictionary containing variable names (keys) and their corresponding objects (values).
A Python expression can access variables in the local namespace and global namespace. If a local variable has the same name as a global variable, the local variable overrides the global variable.
Each function has its own namespace. The scoping rules for class methods are the same as for regular functions.
#Python will intelligently guess whether a variable is local or global, assuming that any variable assigned a value within a function is local.
Therefore, if you want to assign a value to a global variable within a function, you must use the global statement.
#!/usr/bin/python # -*- coding: UTF-8 -*- Money = 2000 def AddMoney(): # 想改正代码就取消以下注释: # global Money Money = Money + 1 print Money AddMoney() print Money
The global VarName expression will tell Python that VarName is a global variable, so that Python will not look for this variable in the local namespace.
For example, we define a variable Money in the global namespace. We then assign a value to the variable Money within the function, and then Python will assume that Money is a local variable. However, we did not declare a local variable Money before accessing it, and the result is an UnboundLocalError. Uncommenting the global statement can solve this problem.
The above is what I want to explain today: namespaces and scopes. Just reading my explanation is just talking on paper. Hands-on practice is the best way to verify what you have learned. Finally, I hope this article can bring some help to you who are learning python.
For more related knowledge, please visit the Python tutorial column on the php Chinese website.
The above is the detailed content of What are python namespaces and scopes? What are its functions?. For more information, please follow other related articles on the PHP Chinese website!