Use modules in Python and python

Source: Internet
Author: User
Tags first string

Use modules in Python and python

Python itself has many built-in very useful modules, which can be used immediately after installation.

The built-in sys module is used as an example to compile a hello module:

#!/usr/bin/env python# -*- coding: utf-8 -*-' a test module '__author__ = 'Michael Liao'import sysdef test():  args = sys.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()

Rows 1st and 2nd are standard comments, and 1st comments can make this hello. the py file runs directly on Unix, Linux, and Mac, with 2nd lines of comments. the py file itself uses standard UTF-8 encoding;

Line 2 is a string that indicates the module's document comment. The first string of any module code is considered as the module's document comment;

Use the _ author _ variable in Row 3 to write the author into it, so that when you publish the source code, others can view your name;

The above is the standard file template of the Python module. Of course, you can delete all the files without writing them. However, it is certainly true to follow the standards.

The following is the real code.

You may have noticed that the first step to use the sys module is to import the module:

import sys

After the sys module is imported, we have the variable sys pointing to this module. Using the sys variable, we can access all functions of the sys module.

The sys module has an 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 obtained by running python hello. py is ['hello. py'];

The sys. argv obtained by running python hello. py Michael is ['hello. py', 'Michael].

Finally, we noticed the two lines of code:

if __name__=='__main__':  test()

When we run the hello module file in the command line, the Python interpreter sets the special Variable _ name _ As _ main __, if the hello module is imported elsewhere, if judgment fails. Therefore, this if test allows a module to execute some additional code when running through the command line, the most common is to run the test.

Run hello. py on the command line to check the effect:

$ python hello.pyHello, world!$ python hello.py MichaelHello, Michael!

If you start the Python interaction environment, then import the hello module:

$ pythonPython 2.7.5 (default, Aug 25 2013, 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>>>

The Hello, word !, Because the test () function is not executed.

Hello, word can be printed only when Hello. test () is called! :

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

Alias

You can also use an alias when importing a module. In this way, you can select the most appropriate module based on the current environment during the runtime. For example, the Python standard library generally provides two libraries: StringIO and cStringIO. The interfaces and functions of these two libraries are the same, but cStringIO is written by C and the speed is faster, you will often see the following statement:

Try: import cStringIO as stringiow.t ImportError: # ImportError import StringIO will be captured if the import fails.

In this way, cStringIO can be imported first. If some platforms do not provide cStringIO, You can downgrade to use StringIO. When importing cStringIO, use import... as... to specify the alias StringIO. Therefore, the subsequent code can reference StringIO.

There is also a library like simplejson, which was an independent third-party library before Python 2.6 and has been built in since Python 2.6. Therefore, there will be such a statement:

try:  import json # python >= 2.6except ImportError:  import simplejson as json # python <= 2.5

Since Python is a dynamic language, the same is true for the consistent function signature interfaces. Therefore, no matter which module is imported, subsequent code can work normally.
Scope

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

Normal Functions and variable names are public and can be directly referenced, such as abc, x123, and PI;

Variables like _ xxx _ are special variables and can be directly referenced, but they have special purposes. For example, the above _ author __,__ name _ is a special variable, the document annotations defined by the hello module can also be accessed using the special Variable _ doc _. We do not use this variable name for our own variables;

Functions or variables such as _ xxx and _ xxx are non-public (private) and should not be directly referenced, such as _ abc ,__ abc;

The reason we say that private functions and variables should not be directly referenced, rather than being directly referenced, is because Python does not have a way to completely restrict access to private functions or variables, however, in programming habits, private functions or variables should not be referenced.

Private functions or variables should not be referenced by others. What are their functions? See the example below:

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)

The greeting () function is made public in the module, and the internal logic is hidden using the private function. In this way, calling the greeting () function does not need to care about the details of the internal private function, this is also a very useful method for code encapsulation and abstraction, namely:

All functions that do not need to be referenced externally are defined as private. 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.