Python global variable operation details

Source: Internet
Author: User
Contact Python time is not long, some knowledge points, the mastery is not very solid, I personally more advocating no matter what to learn, first of all must go back to the foundation to hit the very solid, and then go to the high place. Today encountered a Python global variables related operations, encountered a problem, so, here will own problems, do a record, to Long remember heart!!!

The use of global variables in Python, in fact, is not a wise choice, but I still believe that the existence is reasonable, is how you use; Global variables reduce the commonality between modules and functions, so you should try to avoid using global variables in the future programming process.

Use of global variables:

Method One:

In order to facilitate the management of the code, the global variables are uniformly put into a module, and then when using global variables, the global variable module is imported, and the global variables are used in this way;
To define a global variable in a module:

Copy the Code code as follows:


#global. py
Global_1 = 1
Global_2 = 2
Global_3 = ' Hello world '


Then import the global variable definition module in a module and use the global variable in the new module:
Copy CodeThe code is as follows:


Import Globalvalues

Def printglobal ():
Print (Globalvalues.global_1)
Print (Globalvalues.global_3)
Globalvalues.global_2 + = 1 # Modify values

if __name__ = = ' __main__ ':
Printglobal ()
Print (globalvalues.global_2)

Method Two:

Define the global variable directly in the module and then use it directly in the function to OK. However, when using global variables, you must identify them with the global keyword in the function:

Copy the Code code as follows:


CONSTANT = 0

Def modifyglobal ():
Global CONSTANT
Print (CONSTANT)
CONSTANT + = 1

if __name__ = = ' __main__ ':
Modifyglobal ()
Print (CONSTANT)

Complete explanation!!!

  • Related Article

    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.