Familiar with Python Import Module

Source: Internet
Author: User
This article mainly explains the basic import module method, starting with the definition of the module, and talking about how to write the module by yourself. it is very simple and practical. if you need it, refer Recognition module

For the module, we have already covered some of the previous examples, such as: import random (to obtain the random number module ). In order to have a clear understanding of the module, you should first look at the module. here we will select its definition in the official document:

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.

They are all foreign code. can you translate them? No! Let's just talk about the key points:
• The module is a file containing python statements.
• The module name is the file name (not the extension. py)

So where is the import random file?

Let's look at the help () function, the magic weapon we once talked about:

The code is as follows:


>>> Help (random)

Then, the following error occurs:

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

Here we can clearly tell you that the file of the random module is/usr/local/lib/python2.7/random. py (note: This address is the address on my computer, which may be different from that on the official website. especially if the official website uses windows, it must be different from me .)

At this time, the official may have doubts. How did the import find the file? How to write similar files? Don't worry. I will always come here.

Standard Library

After reading the preceding random example, the viewer may immediately think of a question: has someone written many common functions into modules? Then the user only needs to call it in a similar way. Indeed, as shown above, it is not written by a programmer, but installed on a computer when python is installed. Observe the file storage address and you will know.

Based on the above address, I will list the files in/usr/local/lib/python2.7/. these files are similar to the random module. as python is installed, they are standard, give them a name "standard module library", or "standard library" for short ".

This figure lists a few module files in this directory.

The standard library of Python is an integral part of Python and a powerful tool for Python, allowing programming to get twice the result with half the effort.

If the visitor has time, visit https://docs.python.org/2/library/to list the usage of all standard databases.

One thing, please note: For the standard library, I am afraid it cannot be remembered because there are too many contents. You don't have to remember it. you just need to know that there is such a thing. When writing a program, do you have to think about the standard library support for something? Then you can search on google or the address given above.

Example:

The code is as follows:


>>> Import sys # imported the standard library sys
>>> Dir (sys) # If you do not see the webpage, you can use this method to view the methods (functions) provided by this standard library)
['_ Displayhook _', '_ doc _', '_ egginsert', '_ Thook _', '_ name __', '_ package _', '_ plen', '_ stderr _', '_ stdin _', '_ stdout __', '_ clear_type_cache', '_ current_frames', '_ getframe', '_ mercurial', 'api _ version', 'argv', 'builtin _ lele_names ', 'byteorder ', 'call _ tracing', 'callstats', 'copyright', 'displayhook', 'Dont _ write_bytecode', 'exc _ clear', 'exc _ info ', 'exc _ type', 'mongothook', 'exec _ prefix', 'executable', 'Exit ', 'flags', 'float _ info', 'float _ repr_style ', 'getcheckinterval', 'getdefaultencoding ', 'signature', 'getfilesystemencoding', 'getprofile', 'getcursionlimit ', 'getrefercount', 'getsize', 'gettrace', 'hversion ', '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 ', 'settrack', 'stderr', 'stdin', 'stdout ', 'version', 'version', 'version _ info', 'warnopexception']
>>> Sys. platform # for example
'Linux2'
>>> Sys. version #
'2. 7.6 (default, Nov 13 2013, 19:24:16) \ n [GCC 4.6.3]'

>>> Help (sys. stdin) # This is the method for viewing the specific content of a module.

Standard Library, which is often used in programming. I will not go into details here. You only need to know where to find and how to find the required standard library.

Self-Writing Module

An official may prefer "self-help, clothing, and food" (although it is not necessarily enough). when necessary, you have to write some modules on your own. So how to write the module?

As mentioned above, the module is the. py file. Therefore, as long as some statements are written to a. py file, it is a module. There are no too many secrets.

Create a file named mmmm. py under a directory, as shown in, and edit the file content. Edit and save the settings.

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 figure below shows the directory where the file is located and the python interaction mode is enabled under this directory (I am in ubuntu and the official agent is made of another operating system. pay attention to the path. if there is a problem, can be put on hold for the moment, see below ).

The file mmmm. py is in the current directory.

In the interactive mode, follow the operation method 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 _ # This is empty, because I have never written any instructions.
>>> Mmmm. _ name _ # name
'Mmmm'
>>> Mmmm. _ file _ # file
'Mmmm. py'

Let's look at the following: my_name, pythoner, and web, which are all self-written in the content.

The code is as follows:


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

Web is a variable created through the value assignment statement in the mmmm module. here, It program the attributes of mmmm and can be accessed through the dot number operation. In fact, it is not just a value assignment of this type, other features such as def and class can be used as attributes of the mmmm module.

The code is as follows:


>>> Mmmm. my_name

>>> Mmmm. pythoner

Of course, like operating the standard library, you can use help () to see the specific content 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 class pythoner in module mmmm:

Class pythoner
| Methods defined here:
|
| _ Init _ (self, lang)
|
| Programmer (self)

How to call it? In this way:

The code is as follows:


>>> Mmmm. my_name ("qiwsir ")
Qiwsir

When calling a function in a module, use the module name (import mmmm) + period number + function (note that the function must be followed by parentheses. if there are parameters, the parameters must be included in the brackets ), 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 how to call the classes in the module and the instance methods of the classes by using the bound method. Compared with the past, it seems that an mmmm is added in front.

If you feel this mmmm is 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 ++

This time, you don't need to write mmmm. Which of the two methods is better? No conclusion. In future practices, when and how to use it.

The above uses the from mmmm import, in which the symbol means to import all the data. with this method, you can only import a part, as shown in:

The code is as follows:


>>> From mmmm import my_name # If you have performed the preceding operations, you must disable the interaction mode,
# Restart to see the following process
>>> My_name ("qiwsir ")
Qiwsir
>>> Web # does not import this, so an error is returned.
Traceback (most recent call last ):
File" ", Line 1, in
NameError: name 'web' is not defined

This is the basic import module method. Questions about the official account are still to be saved. In addition, the next loop is decomposed.

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.