Course2-python Functions and modules

Source: Internet
Author: User

A. function

Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.

Functions can improve the modularity of the application, and the reuse of the code. A lot of the built-in functions of Python were mentioned in the previous lesson. Here we mainly talk about the custom function.

1. Define the rules for the function:

Start with the DEF keyword, followed by the function identifier name and parentheses (). The canonical function name

Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.

The first line of the function statement can be a document string-used to hold function comment descriptions.

The function contents begin with a colon and are indented.

Return End Function, optionally returning a value. Return without an expression is equivalent to returning None. Return can be omitted without returning.

By default, parameter values and parameter names are matched in the order defined in the function declaration.

Example 1:

Import time
Import Sys
def logging (message, filename= ' E:\\log.log '):
Try
Print Time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime ()) + "" + Message
FSO = open (filename, ' a ')
Fso.write (Time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime ()) + "" + message+ ' \ n ' + ' \ n ')
Fso.close ()
Except
Err = '. Join (Traceback.format_exception (*sys.exc_info ()))
Print Err

2. Parameters:

1). Required Parameters

Logging ("Test", filename= ' E:\\logtest.log '). The message in Example 1 is a required parameter

2). Named parameters

Logging (message = "My message", Filename= ' E:\\logtest.log ').

3). Default parameters

The filename parameter in Example 1 is considered a default value if it is not passed into the parameter.

Logging ("My Message")

4). Indefinite length parameter

Variable names with an asterisk (*) will hold all unnamed variable arguments. Choose not to send more parameters can also.

As in Example 1, traceback.format_exception (*sys.exc_info ())

3. Anonymous functions

Python uses lambda to create anonymous functions.

1). Lambda is just an expression, and the function body is much simpler than def.

2). The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.

3). The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.

4). Although the lambda function appears to be able to write only one line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.

5). The syntax for the lambda function contains only one statement, as follows:

Lambda [arg1 [, Arg2,..... argn]]:expression

Example 2:

Summ = Lambda Arg1,arg2:arg1 + arg2summ

4. Scope of variables:

1). Global variables

2). Local variables

Variables defined inside a function have a local scope, which defines the owning global scope outside of the function.

Local variables can only be accessed within their declared functions, while global variables are accessible throughout the program. When a function is called, all variable names declared within the function are added to the scope.

Example 3:

Total = 0; # global variable def summ (Arg1, arg2): Total   = arg1 + arg2; # All in this is a local variable.   Print "function local variable:", total   

Two. Module

The module is able to logically organize Python code snippets. Assigning the relevant code to a module makes the code easier to use and easier to understand.

The module is also a Python object, with a random name attribute used to bind or reference.

The module is a file that holds the Python code. Modules can define functions, classes, and variables. The module can also contain executable code.

1. Import the module

1). Import, to use the Python source file, simply execute the import statement in another source file. Import Module1[, module2[,... Modulen]

such as: Import function1

When the interpreter encounters an import statement, the module is imported if it is in the current search path.

A search path is a list of all directories that an interpreter will search first. The import command needs to be placed at the top of the script.

2). From ... import

The FROM statement lets you import a specified section from the module into the current namespace: from modname import name1[, name2[, ... Namen]]

such as: From Pywinauto.application import application

3). From ... import *

It is also possible to import all the contents of a module into the current namespace. from modname import *

Example: from datasources.publicvariables import *

2. Positioning module

When you import a module, the Python parser's search order for the module location is:

1). Current directory

2). If it is not in the current directory, Python searches for each directory under the shell variable PYTHONPATH.

3). If none are found, Python will look at the default path. Under UNIX, the default path is generally/usr/local/lib/python/.

The module search path is stored in the Sys.path variable of the system module. The variable contains the current directory, Pythonpath, and the default directory determined by the installation process.

4). Pythonpath variable

As an environment variable, Pythonpath consists of many directories that are installed in a single list. The syntax of the Pythonpath is the same as the shell variable path.

In Windows systems, the typical pythonpath are as follows:

Set PYTHONPATH=C:\python20\lib;

In Unix systems, the typical pythonpath are as follows:

Set PYTHONPATH=/usr/local/lib/python

3. Namespaces and Scopes

A Python expression can access variables in the local namespace and in the global namespace. If a local variable and a global variable have the same name, the local variable overrides the global variable.

Each function has its own namespace. The scope rules of a method of a class are the same as the usual functions.

Notes: If you want to assign a value to a global variable in a function, you must use the global statement.

4. Dir ()

The Dir () function is a well-ordered list of strings, and the content is a name defined in a module. dir(module_name)

The returned list contains all the modules, variables, and functions defined in a module.

5. Reload ()

When a module is imported into a script, the code at the top-level part of the module is executed only once.

Therefore, if you want to re-execute the code in the top-level part of the module, you can use the reload () function. The function will re-import the previously imported modules. Reload(module_name)

6. Packages in Python

A package is a hierarchical file directory structure that defines a Python application environment consisting of a module and a sub-package, and a sub-package under a sub-package.

Notes: The file must be created under the package directory __init__.py

Course2-python Functions and modules

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.