In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how to use the global of Python. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something from this article.
First answer why there should be global.
A variable is referenced by multiple functions and you want the global variable to be shared and modified by all functions. Some partners may think, this is not easy:
I = 5
Def f ():
Print (I)
Def g ():
Print (I)
Pass
F ()
G ()
Both f and g functions can share the variable I, and the program does not report an error. So they still don't understand why they use global.
However, if you want to increment I, this way:
Def h ():
I + = 1
H ()
Execute the program at this time, bang, there is an error! Throw an exception: UnboundLocalError.
It turns out that the compiler will parse I as a local variable in the function h () when interpreting iDiversion1. Obviously, in this function, the compiler cannot find the definition of variable I, so it will report an error.
Global is proposed to solve this problem.
Within the function h, the compiler is explicitly told that I is a global variable, and then the compiler will look for the definition of I outside the function. After executing iDiversion1, I is also a global variable with a value of 1:
I = 0
Def h ():
Global i
I + = 1
H ()
Print (I)
Recent small example: write a decorator: count the number and time of exception occurrence; implement the object that can be called; find the distance between two points in any dimension; compare two methods of merging dictionaries; calculate and aggregate at the same time; groupby grouping; plotly draw histogram + line chart
After reading the above, do you have any further understanding of how to use Python's global? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.