Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Namespace and scope of Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report