Python topic 6 local variables, global variables, import module variables, pythonglobal

Source: Internet
Author: User

Python topic 6 local variables, global variables, import module variables, pythonglobal

Variables defined in a function have local scopes, and the most advanced variables in a module have global scopes. This document describes global variables, local variables, and methods for importing module variables.

Reference: Python core programming (version 2)

1. Local Variables

The scope of the declared application is called the declared scope. In a process, if the name is included in the Process Declaration, it is the local variable of the process; otherwise, it is non-local. Example:

def foo(x):  print 'x = ',x  x = 200  print 'Changed in foo(), x = ',x x = 100 foo(x) print 'x = ',x 

The output result is as follows:

>>> x = 100 Changed in foo(), x = 200 x = 100 

Define x = 100 in the main block. Python uses the form parameter declared by the function to pass x to the foo () function. In foo (), the value of x is 200, and x is the local variable of the function. Therefore, changing the value of x in the function will not affect the x defined in the main block.

Core notes:

When you search for an identifier, Python first searches for it from the local scope. If the name is not found in the local scope, the variable will be found throughout the local area; otherwise, a NameError exception will be thrown.

The concept of scope is related to the namespace search sequence used to find variables. When a function is executed, all the names in the local namespace are in the local scope. When a variable is searched, the first namespace to be searched. If the variable is not found, the local variable with the same name may be found.

Ii. Global Variables

A feature of global variables is that they survive until the script stops running and their values can be accessed for all functions. However, local variables, like the stacks they store, temporarily exist and only depend on defining whether their functions are active at the current stage. When a function call occurs, its local variables enter the scope of declaring them. At that moment, a new local variable named that object is created. Once the function is complete and the framework is released, the variable will leave the scope.

X = 100 def foo():  global X  print 'foo() x = ',X  X = X + 5  print 'Changed in foo(), x = ',X def fun():  global X  print 'fun() x = ',X  X = X + 1  print 'Changed in fun(), x = ',X if __name__ == '__main__':  foo()  fun()  print 'Result x = ',X 

The output result is as follows:

>>> foo() x = 100 Changed in foo(), x = 105 fun() x = 105 Changed in fun(), x = 106 Result x = 106 

Core notes:

Use global statements to define global variables. When using a local variable with the same name as a global variable, be careful. If you declare the name of the global variable in a function, the name of the global variable can be overwritten by the local variable. Therefore, you should try to add a global statement. Otherwise, the reader of the program may not know where the variable is defined.

You can use the same global statement to specify multiple global variables. For example, global x, y, and z.

When I create a Python crawler, I need to pass the url in the function and crawl the InfoBox of each url page cyclically. At this time, the file write operation can be implemented in two ways: 1. pass the file parameter; 2. by defining the global variable file.

SOURCE = open("F:\\test.txt",'w') def writeInfo(i):  global SOURCE  SOURCE.write('number'+str(i)+'\n') def main():  i=0  while i<50:  writeInfo(i)  print i  i=i+1  else:  print 'End'  SOURCE.close() main() 

PS: In this usage, if we do not use global to declare the global variable SOURCE in the writeInfo () function, we can also use it, but it should be used as an internal variable, because there is no initial value, an error is returned. Python searches for variables in sequence: local variables first, and then global variables.

UnboundLocalError: local variable 'SOURCE' referenced before assignment 

Iii. Module import Variables

The main method is to define the variables in the module in the py file, and then import and use the global variables through import. Example:

Import global_abc def foo (): print global_abc.GLOBAL_A print global_abc.GLOBAL_ B print global_abc.GLOBAL_C = signature + 200 print partition if _ name _ = '_ main _': foo () print global_abc.GLOBAL_A + ''+ global_abc.GLOBAL_ B print global_abc.GLOBAL_C the output is as follows. The global variable structure can be changed. >>> Hello world 300 500 hello world 500

As follows:

PS: 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. At the same time, global variables reduce the versatility between functions or modules. Different functions or modules depend on global variables. Similarly, global variables reduce the readability of the Code. Readers may not know that a certain variable called is a global variable, but in some cases they need to use it inevitably.

Finally, we will not introduce closures and Lambda (equivalent to functions.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.