Tips for hiding Python global variables"

Source: Internet
Author: User

Python global variables do not conform to the relevant rules of parameter passing, so many people do not want to use them frequently unless constants are defined. We will discuss global variables and find the hidden tips. I hope you will gain some gains through this article.

The program is roughly like this:

 
  1. CONSTANT = 0 
  2.  
  3. def modifyConstant() :  
  4.         print CONSTANT  
  5.         CONSTANT += 1  
  6.         return  
  7.  
  8. if __name__ == '__main__' :  
  9.         modifyConstant()  
  10.         print CONSTANT  
  11.  

The running result is as follows:
UnboundLocalError: local variable 'constant' referenced before assignment: Why does the Python global variable become a local variable in the modifyConstant function?
Modify:

 
  1. CONSTANT = 0 
  2.  
  3. def modifyConstant() :  
  4.         print CONSTANT  
  5.         #CONSTANT += 1  
  6.         return  
  7.  
  8. if __name__ == '__main__' :  
  9.         modifyConstant()  
  10.         print CONSTANT  
  11.  

It seems that the function can access global variables.
Therefore, the problem is that, because the variable CONSTANT is modified inside the function, Python considers CONSTANT as a local variable, and print CONSTANT is before CONSTANT + = 1, this error will certainly occur. So, how should I access and modify Python global variables inside the function? The keyword global should be used to modify variables a bit like PHP ):

 
  1. CONSTANT = 0 
  2.  
  3. def modifyConstant() :  
  4.         global CONSTANT  
  5.         print CONSTANT  
  6.         CONSTANT += 1  
  7.         return  
  8.  
  9. if __name__ == '__main__' :  
  10.         modifyConstant()  
  11.         print CONSTANT  
  12.  

If you have any questions about the solution, you may wish to take a look at the above solutions to better understand it and ensure smooth application in practical applications.

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.