Python uses modules

Source: Internet
Author: User
Tags aliases 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 modules, for example, write 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()

Lines 1th and 2nd are standard comments, and the 1th line of comments allows the 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;

The 6th line uses __author__ variables 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 a variable sys pointing to the module, which sys allows access to all the sys functions of the module.

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

python hello.pythe operation obtained sys.argv is [‘‘] ;

python Michaelthe operation obtained sys.argv is [‘‘, ‘Michael] .

Finally, notice the two lines of code:

if __name__==‘__main__‘:    test()

When we run the module file at the command line hello , the Python interpreter places a special variable __name__ __main__ , and if the module is imported elsewhere, the hello if judgment will fail, so this if Testing allows a module to execute some extra code when it runs through the command line, most commonly by running tests.

We can run with the command line to see the effect:

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

If you start the Python interactive 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>>>

When importing, there is no print Hello, word! , because no function is executed test() .

hello.test()to print out when it is called Hello, word! :

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

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 is generally provided StringIO with cStringIO two libraries, the interface and functions of the two libraries are the same, but cStringIO is written in C, faster, so you will often see the wording:

try:    import cStringIO as StringIOexcept ImportError: # 导入失败会捕获到ImportError    import StringIO

This allows you to import first cStringIO . If some platforms are not available cStringIO , you can also downgrade them for use StringIO . cStringIOwhen importing, import ... as ... aliases are specified StringIO so that subsequent code references StringIO work correctly.

There are simplejson libraries like this, 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.


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 by a _ prefix.

Normal functions and variable names are public and can be referenced directly, such as: abc , x123 , PI etc.;

__xxx__Such variables are special variables, can be directly referenced, but there are special purposes, such as the above __author__ , __name__ is a special variable, hello the module definition of the document can also be accessed with special variables __doc__ , our own variables are generally not used this variable name;

Similar _xxx and __xxx such functions or variables are non-public (private), should not be directly referenced, 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 function in the module and greeting() hide the internal logic with the private function, so that the calling greeting() function does not care about 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.

See here, I naturally think if the name of the two modules is the same, then what will happen:

def Same ():     Print ' same '

def Same ():     Print ' same2 '

Import First_same_function_name Import second_same_function_namesecond_same_function_name.same () first_same_function_name.same ( )

Hey, the name of the module must be written, how troublesome, hanging had to be the case of conflict

Python uses 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: 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.