Go to: Python global variables

Source: Internet
Author: User

Avoid using global variables whenever possible. Different modules can freely access global variables, which may lead to unpredictable global variables. For global variables, if programmer A modifies the value of _ A, programmer B also uses _ A, which may cause errors in the program. It is difficult to find and correct such errors.

Global variables reduce the universality between functions or modules. Different functions or modules depend on global variables. Similarly, global variables reduce code readability. Readers may not know that a variable called is a global variable.

However, in some cases, global variables can solve problems that are hard to solve by local variables. Things must be divided into two parts.

Global variables in Python have two flexible usage methods:

1 Statement

Declare the global variable at the beginning of the file,

When using this variable in a specific function, you must declare global variable in advance. Otherwise, the system regards this variable as a local variable.

Constant = 0
(Uppercase global variables for easy identification)

Def modifyconstant ():

Global constant

Print constant

Constant + = 1

Return

If _ name _ = '_ main __':

Modifyconstant ()

Print constant

2 module method (recommended)

Define global variables in a separate module:
# Gl. py
Gl_1 = 'hello'
Gl_2 = 'World'

Used in other modules
# A. py
Import GL

Def hello_world ()
Print Gl. gl_1, GL. gl_2

# B. py
Import GL

Def fun1 ()
Gl. gl_1 = 'hello'
Gl. gl_2 = 'World'

The second method is suitable for sharing variables between different files. To some extent, it avoids the disadvantages of global variables mentioned at the beginning!

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.