Go: Python's global variables

Source: Internet
Author: User

You should try to avoid using global variables. Different modules are free to access global variables, which can lead to unpredictable global variables. For global variables, if programmer a modifies the value of _a, programmer B also uses _a, which can cause errors in the program. Such errors are difficult to detect and correct.

Global variables reduce the commonality between functions or modules, and different functions or modules depend on global variables. Similarly, global variables reduce the readability of the code, and the reader may not know that a variable being called is a global variable.

But at some point, global variables can solve problems that are difficult to solve with local variables. Things must be divided into divided.

There are two kinds of flexible uses of global variables in Python:

1 Declaration Law

Declare the global variable variable at the beginning of the file,

When you use this variable in a specific function, you need to declare the global variable beforehand, otherwise the system treats the variable as a local variable.

CONSTANT = 0 (capitalize the global variable for easy identification)

Def modifyconstant ():
Global CONSTANT
Print CONSTANT
CONSTANT + = 1
Return

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

2 Module method (recommended)

Define the global variables in a separate module:
#gl. py
Gl_1 = ' Hello '
gl_2 = ' World '

Use 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, which is applicable to the sharing of variables between different files, and to some extent avoids the drawbacks of the global variables mentioned at the beginning, recommend!

Go: Python's global variables

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.