Python Induction (vi) _ Module variable scope

Source: Internet
Author: User
Tags variable scope

test_module2.py:

#-*-Coding:utf-8-*-
"""
Scope of the test module variable

Summarize:
1 variables of other modules, anywhere in the current module, including functions can be passed through the module. Variable access, including read and write
2 variables of this module, when accessed in a function, the first occurrence is a read operation, directly using the first occurrence is a write operation, it must be gloabl declared otherwise into a local variable
3 refer to External module variables at the head of this module, all functions are accessible. If you import external module variables only in one of the functions in this module
Accessible only in this function, external module variables cannot be accessed in this module, other functions of this module
4 Import module, executes multiple times, actually executes only the first time, reload reload
"""
Import Test_module

b = 8

Def f1 ():
Test_module.a = 5

def f2 ():
Def f22 ():
Print Test_module.a
F22 ()

Def f3 ():
Print B # is the first time to use B is read, is a global variable

def f4 ():
b = 9 # The first time to use B is assignment, is a function local variable

def f5 ():
Global B # Force Globals
B = 9

Print Test_module.a
F1 ()
Print Test_module.a
F2 ()
Print Test_module.a

Import Test_module # Executes the importing module again and no longer executes
Print Test_module.a

Reload (test_module) # Reload really run the module again
Print Test_module.a

print '-------1 '
F3 ()
Print B
F4 ()
Print B
F5 ()
Print B
F3 ()

"""
Out:
3
5
5
5
5
3
-------1
8
8
8
9
9

"""

test_module.py:

# -*-coding:utf-8-*-a = 3

Python Induction (vi) _ Module variable scope

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.