With old Ziko Python's import module

Source: Internet
Author: User
Understanding Modules

For the module, in the previous examples, it has been involved, such as once had: import random (Get the stochastic module). In order to be able to have a clear understanding of the module, first to see what module, here to choose the Official document definition of it:

The code is as follows:


A module is a file containing Python definitions and statements. The file name is the module name with the suffix. Py appended. Within a module, the module ' s name (as a string) is available as the value of the global variable name.

Are all in the foreign language, translate it? No! Or just say the main points:
• The module is a file containing Python statements
• The module name is the file name (do not extend. py)

So, where is the import random file?

With the magic that I used to say: the Help () function to see:

The code is as follows:


>>> Help (Random)

Then it appears:

The code is as follows:


NAME
Random-random variable generators.

FILE
/usr/local/lib/python2.7/random.py

MODULE DOCS
Http://docs.python.org/library/random

DESCRIPTION
...

It is very obvious here that the files of the random module are:/usr/local/lib/python2.7/ random.py (Note: This address is the address of my computer, it may be different from crossing, especially if crossing is using Windows, it must be different from mine. )

Crossing may be in doubt at this time, import is how to find the file? How do you write similar files? Don't worry, I'll be one by one.

Standard library

Looking at the example of the previous random, crossing may immediately think of a question: Has someone already written a lot of common functions into modules? Then the user simply needs to call it in a similar way. It is true that, as shown above, it is not written by a programmer at the time of use, but is installed in the computer when the Python is installed. Look at the file storage address and you'll know.

According to the above address, I list the files inside the/usr/local/lib/python2.7/, these files are similar to the random module, because it is a Python installation, it is standard, give them a name "standard module Library", referred to as "standard library".

This diagram lists a very small portion of the module files that exist in this directory.

Python's standard library is an integral part of Python and a powerful tool for Python to make programming less effective.

If crossing has time, visit frequently: https://docs.python.org/2/library/, which lists all of the standard library usage methods.

One thing, please crossing special attention, for the standard library, because the content is too much, I am afraid I can't remember. You don't have to be able to remember, just know there's something. If you are writing a program, be sure to think about something, is there a standard library support it? Then go to Google or the address given above to search.

Example:

The code is as follows:


>>> Import SYS #导入了标准库sys
>>> dir (SYS) #如果不到网页上看, this way you can see the various methods (functions) provided by this standard library
[' __displayhook__ ', ' __doc__ ', ' __egginsert ', ' __excepthook__ ', ' __name__ ', ' __package__ ', ' __plen ', ' __stderr__ ', ' __ Stdin__ ', ' __stdout__ ', ' _clear_type_cache ', ' _current_frames ', ' _getframe ', ' _mercurial ', ' api_version ', ' argv ', ' Builtin_module_names ', ' byteorder ', ' call_tracing ', ' callstats ', ' copyright ', ' displayhook ', ' dont_write_bytecode ', ' Exc_clear ', ' exc_info ', ' exc_type ', ' excepthook ', ' exec_prefix ', ' executable ', ' exit ', ' flags ', ' float_info ', ' Float_ Repr_style ', ' getcheckinterval ', ' getdefaultencoding ', ' getdlopenflags ', ' getfilesystemencoding ', ' getprofile ', ' Getrecursionlimit ', ' getrefcount ', ' getsizeof ', ' gettrace ', ' hexversion ', ' last_traceback ', ' last_type ', ' Last_value ' , ' Long_info ', ' maxint ', ' maxsize ', ' maxunicode ', ' meta_path ', ' modules ', ' path ', ' path_hooks ', ' path_importer_cache ', ' Platform ', ' prefix ', ' ps1 ', ' ps2 ', ' py3kwarning ', ' setcheckinterval ', ' setdlopenflags ', ' setprofile ', ' Setrecursionlimit ', ' settrace ', ' stderr ', ' stdin ', ' stdout ', ' subversion ', ' versIon ', ' version_info ', ' warnoptions ']
>>> Sys.platform #比如这个
' Linux2 '
>>> sys.version #还有这个
' 2.7.6 (default, Nov, 19:24:16) \n[gcc 4.6.3] '

>>> Help (Sys.stdin) #这是查看某个模块方法具体内容的方式

Standard library, often used in programming. Don't dwell on it here. As long as crossing can know where to find, how to find the required standard library.

Write your own module

Crossing may prefer to "do it yourself, clothed" (though it is not necessarily clothed), and in some cases it is necessary to write some modules yourself. So how do you write a module?

As explained above, the module is a. py file, so as long as you write some statements into a. py file, it is a module. There is not much secret.

A file is created under a directory, the name is: mmmm.py, as shown, and then edit the contents of this file. Save it after editing it well.

The code is the file content:

The code is as follows:


#!/usr/bin/env python
#coding: Utf-8

web = "Https://qiwsir.github.io"

def my_name (name):
Print Name

Class Pythoner:
def __init__ (Self,lang):
Self.lang = Lang
def programmer (Self):
Print "Python programmer language is:", Self.lang

The diagram is the directory where the file is located, and in this directory open the Python interactive mode (I am under Ubuntu, Crossing is another operating system, note the path, if you encounter problems, you can temporarily shelve, see below).

As you can see, this file is in the current directory: mmmm.py

In interactive mode, emulate the operation of the standard library module:

The code is as follows:


>>> Import MMMM
>>> dir (MMMM)
[' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' my_name ', ' Pythoner ', ' web ']
>>> mmmm.__doc__ #这个是空的, exactly, because I never wrote any documentation.
>>> mmmm.__name__ #名字
' MMMM '
>>> mmmm.__file__ #文件
' mmmm.py '

Look at the back: my_name,pythoner,web, all I wrote in the content.

The code is as follows:


>>> Mmmm.web
' Https://qiwsir.github.io '

The web is a variable created by an assignment statement in the module mmmm, where it programmed the properties of the mmmm to be accessed through the point-number operation, not just the assignment of this type, but the properties of the MMMM module through Def,class.

The code is as follows:


>>> Mmmm.my_name

>>> Mmmm.pythoner

Of course, as with the standard library, you can use Help () to see the specifics of these attributes:

The code is as follows:


>>> Help (Mmmm.my_name)

Help on function my_name in module MMMM:

My_name (name)

>>> Help (Mmmm.pythoner)

Help on the class Pythoner in module mmmm:

Class Pythoner
| Methods defined here:
|
| __init__ (self, Lang)
|
| Programmer (Self)

How to invoke it? This allows you to:

The code is as follows:


>>> mmmm.my_name ("Qiwsir")
Qiwsir

When calling a function in a module, use the name of the module (import mmmm) + dot + function (Note that there are parentheses after the function, if there are arguments, the parentheses are followed by parameters), i.e. Module_name.funciton (*args)

The code is as follows:


>>> py = Mmmm.pythoner ("C + +")
>>> Py.programmer ()
Python Programmer Language Is:c++

The above two lines demonstrate the use of a bound method to invoke a class in the module and an instance method of the class. Compared with the past, it seems that there is a mmmm in front.

If you feel this mmmm is more troublesome, you can use from, specifically:

The code is as follows:


>>> from MMMM import *
>>> my_name (' Qiwsir ')
Qiwsir
>>> Web
' Https://qiwsir.github.io '
>>> py = Pythoner ("C + +")
>>> Py.programmer ()
Python Programmer Language Is:c++

I don't have to write so mmmm this time. Two ways, which is better? There is no verdict. Crossing in the practice of the future experience, when in what way.

The above uses the from MMMM import, where the symbol, means that all the imports come in, with this method, can also only import part, as:

The code is as follows:


>>> from mmmm import my_name #如果看官前面运行了上述操作, you need to turn off interactive mode,
#再重启 to see the following procedure
>>> my_name ("Qiwsir")
Qiwsir
>>> Web #没有import这个, so error.
Traceback (most recent):
File " ", line 1, in
Nameerror:name ' web ' is not defined

This is the basic Import module method. Crossing doubts, but also to save. and listen to tell.

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