Tutorials for using modules in Python

Source: Internet
Author: User
Tags first string
Python itself has many very useful modules that can be used immediately as soon as the installation is complete.

Our built-in sys module, for example, writes a Hello module:

#!/usr/bin/env python#-*-coding:utf-8-*-' a test module ' __author__ = ' Michael Liao ' import sysdef Test ():  args = s YS.ARGV  If Len (args) ==1:    print ' Hello, world! '  Elif len (args) ==2:    print ' Hello,%s! '% args[1]  else:    print ' Too many arguments! ' If __name__== ' __main__ ':  Test ()

Lines 1th and 2nd are standard comments, and line 1th comments allow the hello.py file to run directly on Unix/linux/mac, and the 2nd line comment indicates that the. py file itself uses standard UTF-8 encoding;

Line 4th is a string representing the document comment of the module, and the first string of any module code is treated as a document comment of the module;

Line 6th uses the __author__ variable to write the author in, so that when you open the source code, others will be able to admire your name;

The above is the Python module standard file template, of course, you can also delete all do not write, but, according to the standard is certainly correct.

The real Code section starts at the back.

You may have noticed that the first step in using the SYS module is to import the module:

Import Sys

After importing the SYS module, we have the variable sys pointing to the module, and using the SYS variable, we can access all the functions of the SYS module.

The SYS module has a argv variable that stores all the parameters of the command line with the list. ARGV has at least one element, because the first parameter is always the name of the. py file, for example:

The sys.argv that runs Python hello.py is [' hello.py '];

The sys.argv of running Python hello.py Michael is [' hello.py ', ' Michael '.

Finally, notice the two lines of code:

If __name__== ' __main__ ':  Test ()

When we run the Hello module file at the command line, the Python interpreter __name__ a special variable to __main__, and if the Hello module is imported elsewhere, the If judgment fails, so This if test allows a module to execute some extra code while running through the command line, most commonly running tests.

We can run hello.py with the command line to see the effect:

$ python hello.pyhello, world!$ python hello.py Michaelhello, michael!

If you start the Python interactive environment, then import the Hello module:

$ Pythonpython 2.7.5 (default, 00:04:04) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on Darwintype "Help", "copyright", "credits" or "license" for more information.>>> import hello>>>

When importing, no Hello is printed, word!, because the test () function is not executed.

When you call Hello.test (), you can print out Hello, word!:

>>> hello.test () Hello, world!

Alias

When importing modules, you can also use aliases so that you can select the most appropriate modules at run time based on your current environment. For example, the Python standard library generally provides Stringio and Cstringio two libraries, the interface and functions of the two libraries are the same, but the Cstringio is written in C, faster, so you will often see this way:

Try: Import  Cstringio as stringioexcept importerror: # Importing failed to capture Importerror  import Stringio

This allows you to import Cstringio as a priority. If some platforms do not provide Cstringio, you can also downgrade the use of Stringio. When importing Cstringio, use import ... as ... Alias Stringio is specified, so subsequent code references Stringio to work correctly.

There are libraries like Simplejson, which are independent third-party libraries before Python 2.6 and built from 2.6, so there's a way to do this:

Try:  import JSON # python >= 2.6except importerror:  import Simplejson as JSON # python <= 2.5

Since Python is a dynamic language, the function signature consistent interface is the same, so no matter which module you import, subsequent code will work correctly.
Scope

In a module, we may define many functions and variables, but some functions and variables we want to use for others, some functions and variables we want to use only within the module. In Python, this is done through the _ prefix.

Normal functions and variable names are public and can be directly referenced, for example: ABC,X123,PI, etc.;

A variable like __xxx__ is a special variable that can be referenced directly, but has a special purpose, such as the __author__,__name__ above is a special variable, and the document annotation defined by the Hello module can also be accessed with a special variable __doc__. Our own variables are generally not used in this variable name;

Functions or variables such as _xxx and __xxx are non-public (private) and should not be referenced directly, such as _ABC,__ABC, etc.

The reason why we say that private functions and variables should not be directly referenced, rather than "cannot" be directly referenced, is because Python does not have a way to completely restrict access to private functions or variables, but from a programming habit should not refer to private functions or variables.

Private functions or variables should not be referenced by others, what is the use of them? Take a look at the example:

def _private_1 (name):  return ' Hello,%s '% namedef _private_2 (name):  return ' Hi,%s '% namedef greeting (name): 
  if len (name) > 3:    return _private_1 (name)  else:    return _private_2 (name)

We expose the greeting () function in the module and hide the internal logic with the private function, so that calling the greeting () function does not concern the internal private function details, which is also a very useful way to encapsulate and abstract the code, namely:

Functions that do not need to be referenced externally are all defined as private, and only functions that need to be referenced externally are defined as public.

  • 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.