"Python Learning-4" reusable functions and modules

Source: Internet
Author: User
Tags variable scope

1. Custom Functions

The custom function format is as follows:

def < function name > (Parameter list):    < Function statement >    < return value >
# !/usr/bin/python # define functions, print numbers def PRINTNUM5 ():     # The range function, which generates the list collection, has 3 entry parameters: Start (optional, start number), stop (number of stops, number of builds does not contain loveme), step     for  in range (1,5+1):        print(i);p rintNum5 ();

Functions with Parameters:

# !/usr/bin/python # define functions, Print List data def printnum (x):      for inch x:         Print (i);p rintnum (['ls','pwd', 6, 9, ' CD ']);

Functions with default parameters:

#!/usr/bin/python#For x, the default x is 2,y 5defCube (x=2,y=5):    returnx**y;Print(Cube ());#x, y both use default valuesPrint(Cube (3));#x set to 3,y use default valuePrint(Cube (3,2));#x, y do not use default valuesPrint(Cube (y=3));#x with default value, Y set to 3Print(Cube (y=2,x=8));#disrupting the order of the parameters of communication

Pass any of the arguments:

#!/usr/bin/python#pass any parameter: If the parameter name is preceded by an asterisk "*", the argument is a variable-length parameterdefAddnum (*nums): Result=0;  forIinchNums:result+=i; returnresult;Print(Addnum ());#0Print(Addnum (1,3));#4Print(Addnum (8,8,6));# A

2. Variable Scope

 #  !/usr/bin/python  def   fun (x): a  = [1 print   (a); a  = [3,4,5];fun ( 2); #   A does not change  print  (a); 
# !/usr/bin/python def Fun (x):     Global A;    # set A as global variable    A = [1];    A.append (x);     Print  = [3,4,5];    # global variable fun (2);            # A has changed Print (a);

3. Declaring a function with lambda

Using lambda to declare an anonymous function, Lambda declares a simple function.

The print () function cannot be used in a lambda function

# !/usr/bin/python # the benefit of a lambda function is simplicity. Lambda x:x*x+1    #  declares a lambda function print(Fun (3)); Print (fun);

4. Reusable structure: Python module

The modules in Python are actually Python scripts that contain functions or classes.

For a large script, it is often necessary to refine the functionality into individual modules.

Import Module notation:

Import Module name import module name as new name from Module name Import function name

Using the "From Module name Import function name" and "Import module name", the difference is that the former can directly use the function name to call the function, which requires "module name. Function name" Call function.

# !/usr/bin/python Import Math Print (Math.sqrt ());  from Import sqrt Print (sqrt (81));

Reload the module:

# !/usr/bin/python Import OS Import  = imp.reload (OS)    #  re-loading module print(a);

Write a module:

Includes two files, one is a module file, and the other is a call file.

# file mypart.py def Show ():     Print ("This isshow""mypart-name";
# !/usr/bin/python # file test.py Import mypartmypart.show (); Print (Mypart.name);

Where are the modules in Python found:

Well-written module, if not to call the file in the same directory, then how to find it, or how to place their own modules?

# !/usr/bin/python Import SYS Print # See which modules retrieve the path

If a new module is added to the modules directory under the current path, how can I add a path?

# !/usr/bin/python Import SYS Import Ossys.path.append (OS.GETCWD ()+'\\module'#  adds a directory where OS.GETCWD ( ) method to return the current working directory Print(sys.path);
Import mypartmypart.show ();

For a module script, Python compiles it into a. PYC bytecode file after it runs, and for non-module scripts, Python no longer runs the file and compiles it into bytecode form.

How to view the function names provided by the module:

# !/usr/bin/python Import SYS Import Ossys.path.append (OS.GETCWD ()+'\\module'#  os.getcwd () method is used to return the current working directory Import  mypartprint(dir (OS))        #  using dir Function view the function name provided by the module print(dir (mypart))

For each of the above to add sys.path, in fact, is very inconvenient, but there is a solution, is to use the package. The package is actually a path relative to the current directory.

# !/usr/bin/python Import Module.mypart Print (dir (module.mypart)) module.myPart.show ()

A little more concise:

# !/usr/bin/python Import Module.mypart as Mypart Print (dir (mypart)) mypart.show ()

"Python Learning-4" reusable functions and modules

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.