search
Python learning--moduleDec 09, 2016 pm 02:25 PM

模块

简介

        你已经学习了如何在你的程序中定义一次函数而重用代码。如果你想要在其他程序中重用很多函数,那么你该如何编写程序呢?你可能已经猜到了,答案是使用模块。模块基本上就是一个包含了所有你定义的函数和变量的文件。为了在其他程序中重用模块,模块的文件名必须以.py为扩展名。
        模块可以从其他程序输入以便利用它的功能。这也是我们使用Python标准库的方法。
        下面的例子告诉我们如何使用标准库模块。

import sys
print 'The command line arguments are:'
for i in sys .argv:
    print i
    
print '\n\nThe PYTHONPATH is' , sys .path, '\n'

 输出

The command line arguments are:
D:\HelloWord\src\moudle\test\sysModuleTest.py
The PYTHONPATH is ['D:\\HelloWord\\src\\moudle\\test', 'D:\\HelloWord\\src', 
'D:\\Java\\Python27\\python27.zip', 'D:\\Java\\Python27\\DLLs', 'D:\\Java\\Python27\\lib', 
'D:\\Java\\Python27\\lib\\plat-win', 'D:\\Java\\Python27\\lib\\lib-tk', 
'D:\\Java\\Python27', 'D:\\Java\\Python27\\lib\\site-packages']

 首先,我们利用import语句输入sys模块。
        当Python执行import sys语句的时候,它在sys.path变量中所列目录中寻找sys.py模块。如果找到了这个文件,这个模块的主块中的语句将被运行,然后这个模块将能够被你使用。
        sys模块中的argv变量通过使用点号指明,sys.argv这种方法的一个优势是这个名称不会与任何在你的程序中使用的argv变量冲突。另外,它也清晰地表明了这个名称是sys模块的一部分。
        sys.argv变量是一个字符串的列表。
        注意:1)Python从0开始计数,而非从1开始。

                   2)初始化过程仅在我们第一次输入模块的时候进行。

                   3)“sys”是“system”的缩写。

 

字节编译的.pyc文件

        输入一个模块相对来说是一个比较费时的事情,所以Python做了一些技巧,以便使输入模块更加快一些。一种方法是创建字节编译的文件,这些文件以.pyc作为扩展名。字节编译的文件与Python变换程序的中间状态有关。当你在下次从别的程序输入这个模块的时候,.pyc文件是十分有用的,因为一部分输入模块所需的处理已经完成了。另外,这些字节编译的文件也是与平台无关的。

 

from..import语句

如果你想要直接输入argv变量到你的程序中(避免在每次使用它时打sys.),那么你可以使用from sys import argv语句。如果你想要输入所有sys模块使用的名字,那么你可以使用from sys import *语句。这对于所有模块都适用。一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。

模块的__name__

每个模块都有一个名称,在模块中可以通过语句来找出模块的名称。当一个模块被第一次输入的时候,这个模块的主块将被运行。假如我们只想在程序本身被使用的时候运行主块,而在它被别的模块输入的时候不运行主块,我们该怎么做呢?这可以通过模块的name属性完成。
使用模块的__name__的方法见下面示例

Python代码  

if __name__ == '__main__' :  

    print 'This program is being run by itself'  

else :  

 print 'I am being imported from another module'  

输出

Python代码  

$ python using_name.py  
This program is being run by itself

$ python  

>>> import using_name  
I am being imported from another  
module  
>>>

        每个Python模块都有它的__name__,如果它是'__main__',这说明这个模块被用户单独运行,我们可以进行相应的恰当操作。 

制造你自己的模块

        创建你自己的模块是十分简单的,你一直在这样做!每个Python程序也是一个模块。你已经确保它具有.py扩展名了。下面这个例子将会使它更加清晰。
        创建你自己的模块的方法见下面示例:

        1.首先,我们先创建一个自己的模块,它与我们普通的Python程序相比并没有什么特别之处。

Python代码  

def sayhi ():  
    print 'Hi, this is mymodule speaking.'  
version = '0.1'

        2.然后,看看如何在我们别的Python程序中使用这个模块。

Python代码  

import mymodule  
  
mymodule.sayhi()  
print 'Version' , mymodule.version

输出

Python代码  

Hi, this is mymodule speaking.  
Version 0.1

dir()函数

You can use the built-in dir function to list module-defined identifiers. Identifiers include functions, classes, and variables. When you supply dir() with a module name, it returns a list of names defined by the module. If no arguments are provided, it returns a list of names defined in the current module.


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

How to solve the permissions problem encountered when viewing Python version in Linux terminal?How to solve the permissions problem encountered when viewing Python version in Linux terminal?Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Scraping Webpages in Python With Beautiful Soup: Search and DOM ModificationScraping Webpages in Python With Beautiful Soup: Search and DOM ModificationMar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

What are some popular Python libraries and their uses?What are some popular Python libraries and their uses?Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to Create Command-Line Interfaces (CLIs) with Python?How to Create Command-Line Interfaces (CLIs) with Python?Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools