Python global variable operation details, python global variable details

Source: Internet
Author: User

Python global variable operation details, python global variable details

I have not been familiar with Python for a long time. I do not have a solid grasp of some knowledge points. I personally advocate that no matter what I want to learn, I must first go back to the basics and go to the heights. Today I encountered operations related to global variables in Python, and encountered problems. So here I will record my problems and keep a long record !!!

When using global variables in Python, I personally think it is not a wise choice; but I still firmly believe that it is reasonable to exist because of how you use it; global variables reduce the versatility between modules and functions. Therefore, we should avoid using global variables in future programming.

Use of global variables:

Method 1:

To facilitate code management, you can place global variables in a single module. Then, when using global variables, You can import them to the global variable module. In this way, you can use global variables;
Define global variables in a module:

Copy codeThe Code is as follows:
# Global. py
GLOBAL_1 = 1
GLOBAL_2 = 2
GLOBAL_3 = 'Hello world'

Then, import the global variable definition module into a module and use global variables 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 2:

Define global variables directly in the module, and then use them directly in the function. However, when using global variables, you must use the global keyword in the function for identification:

Copy codeThe Code is as follows:
CONSTANT = 0

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

If _ name _ = '_ main __':
ModifyGlobal ()
Print (CONSTANT)

The explanation is complete !!!

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.