跟老齐学Python之Import 模块
认识模块
对于模块,在前面的一些举例中,已经涉及到了,比如曾经有过:import random (获取随机数模块)。为了能够对模块有一个清晰的了解,首先要看看什么模块,这里选取官方文档中对它的定义:
代码如下:
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.
都是洋码子,翻译一下不?不!还是只说要点:
•模块就是一个含有python语句的文件
•模块名就是文件名(不要扩展名.py)
那么,那个import random的文件在哪里呢?
用曾经讲过的那个法宝:help()函数看看:
代码如下:
>>> help(random)
然后就出现:
代码如下:
NAME
random - Random variable generators.
FILE
/usr/local/lib/python2.7/random.py
MODULE DOCS
http://docs.python.org/library/random
DESCRIPTION
...
这里非常明显的告诉我们,random模块的文件就是: /usr/local/lib/python2.7/random.py(注意:这个地址是我的计算机中的地址,可能跟看官的不一样,特别是如果看官用的是windows,肯定跟我这个不一样了。)
看官这时候可能有疑问了,import是怎么找到那个文件的?类似文件怎么写?不用着急,这些我都会一一道来。
标准库
看了前面的random这个例子,看官可能立刻想到一个问题:是不是已经有人把很多常用的功能都写成模块了?然后使用者只需要用类似方法调用即可。的确是,比如上面显示的,就不是某个程序员在使用的时候自己编写的,而是在安装python的时候,就被安装在了计算机里面。观察那个文件存储地址,就知道了。
我根据上面得到的地址,列出/usr/local/lib/python2.7/里面的文件,这些文件就是类似random的模块,由于是python安装就有的,算是标配吧,给它们一个名字“标准模块库”,简称“标准库”。
这张图列出了很少一部分存在这个目录中的模块文件。
Python的标准库(standard library)是Python的一个组成部分,也是Python为的利器,可以让编程事半功倍。
如果看官有时间,请经常访问:https://docs.python.org/2/library/,这里列出了所有标准库的使用方法。
有一点,请看官特别注意,对于标准库而言,由于内容太多,恐怕是记不住的。也不用可以的去记忆,只需要知道有这么一个东西。如果在编写程序的时候,一定要想到,对于某个东西,是不是会有标准库支持呢?然后就到google或者上面给出的地址上搜索。
举例:
代码如下:
>>> import sys #导入了标准库sys
>>> dir(sys) #如果不到网页上看,用这种方法可以查看这个标准库提供的各种方法(函数)
['__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 13 2013, 19:24:16) \n[GCC 4.6.3]'
>>> help(sys.stdin) #这是查看某个模块方法具体内容的方式
标准库,在编程中经常用到。这里不赘述。只要看官能够知道在哪里找、如何找所需要的标准库即可。
自己编写模块
看官可能比较喜欢“自己动手,丰衣足食”(虽然真的不一定是丰衣足食),在某些必要的时候,还真得自己动手写一些模块。那么怎么编写模块呢?
前面已经交代,模块就是.py文件,所以,只要将某些语句写到一个.py文件中,它就是一个模块了。没有什么太多的秘密。
在某个目录下面建立了一个文件,名称是:mmmm.py,如下图所示,然后编辑这个文件内容。编辑好后保存。
代码是文件内容:
代码如下:
#!/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
图示是文件所在目录,并且在该目录下打开了python的交互模式(我这是在ubuntu下,看官是别的操作系统的化,注意路径,如果遇到问题,可以暂时搁置,看下文)。
从图中可以看出,当前目录中有这个文件:mmmm.py
在交互模式下,仿照对标准库模块的操作方式:
代码如下:
>>> import mmmm
>>> dir(mmmm)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'my_name', 'pythoner', 'web']
>>> mmmm.__doc__ #这个是空的,正是,因为我未曾写过任何文档说明
>>> mmmm.__name__ #名字
'mmmm'
>>> mmmm.__file__ #文件
'mmmm.py'
再看后面的:my_name,pythoner,web,都是我在内容中自己写的。
代码如下:
>>> mmmm.web
'https://qiwsir.github.io'
web是模块mmmm中的一个通过赋值语句建立的变量,在这里,它编程了mmmm的属性,能够通过点号运算访问,其实不仅仅是这类型的赋值,其它通过def,class等,都能做为mmmm模块的属性。
代码如下:
>>> mmmm.my_name
>>> mmmm.pythoner
当然,跟操作标准库一样,一样能够使用help()来看看这些属性的具体内容:
代码如下:
>>> 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)
怎么调用呢?这样即可:
代码如下:
>>> mmmm.my_name("qiwsir")
qiwsir
当调用模块中的函数的时候,用模块的名称(import mmmm)+点号+函数(注意,函数后面要有括号,如果有参数,括号里面跟参数),即 module_name.funciton(*args)
代码如下:
>>> py = mmmm.pythoner("c++")
>>> py.programmer()
python programmer language is: c++
上面两行,则是演示用绑定的方法调用模块中的类以及类的实例方法。跟以往的相比较,似乎都是在前面多了一个mmmm.
如果感觉这个mmmm比较麻烦,可以用from,具体是这样的:
代码如下:
>>> from mmmm import *
>>> my_name('qiwsir')
qiwsir
>>> web
'https://qiwsir.github.io'
>>> py = pythoner("c++")
>>> py.programmer()
python programmer language is: c++
这次不用总写那么mmmm了。两种方式,哪个更好呢?没有定论。看官在以后的实践中体会,什么时候用什么方式。
上面用from mmmm import ,其中符号,表示将所有的都import进来,用这个方法,也可以只import一部分,如同:
代码如下:
>>> from mmmm import my_name #如果看官前面运行了上述操作,需要关闭交互模式,
#再重启,才能看到下面过程
>>> my_name("qiwsir")
qiwsir
>>> web #没有import这个,所以报错。
Traceback (most recent call last):
File "
NameError: name 'web' is not defined
这就是基本的import模块方法。看官的疑问,还要存着。且听下回分解。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics
![WLAN expansion module has stopped [fix]](https://img.php.cn/upload/article/000/465/014/170832352052603.gif?x-oss-process=image/resize,m_fill,h_207,w_330)
If there is a problem with the WLAN expansion module on your Windows computer, it may cause you to be disconnected from the Internet. This situation is often frustrating, but fortunately, this article provides some simple suggestions that can help you solve this problem and get your wireless connection working properly again. Fix WLAN Extensibility Module Has Stopped If the WLAN Extensibility Module has stopped working on your Windows computer, follow these suggestions to fix it: Run the Network and Internet Troubleshooter to disable and re-enable wireless network connections Restart the WLAN Autoconfiguration Service Modify Power Options Modify Advanced Power Settings Reinstall Network Adapter Driver Run Some Network Commands Now, let’s look at it in detail

This article details methods to resolve event ID10000, which indicates that the Wireless LAN expansion module cannot start. This error may appear in the event log of Windows 11/10 PC. The WLAN extensibility module is a component of Windows that allows independent hardware vendors (IHVs) and independent software vendors (ISVs) to provide users with customized wireless network features and functionality. It extends the capabilities of native Windows network components by adding Windows default functionality. The WLAN extensibility module is started as part of initialization when the operating system loads network components. If the Wireless LAN Expansion Module encounters a problem and cannot start, you may see an error message in the event viewer log.

1. Introduction to the sys module The os module introduced earlier is mainly for the operating system, while the sys module in this article is mainly for the Python interpreter. The sys module is a module that comes with Python. It is an interface for interacting with the Python interpreter. The sys module provides many functions and variables to deal with different parts of the Python runtime environment. 2. Commonly used methods of the sys module. You can check which methods are included in the sys module through the dir() method: import sys print(dir(sys))1.sys.argv-Get the command line parameters sys.argv is used to implement the command from outside the program. The program is passed parameters and it is able to obtain the command line parameter column

Preface This article continues to introduce the Python collection module. This time it mainly introduces the named tuples in it, that is, the use of namedtuple. Without further ado, let’s get started – remember to like, follow and forward~ ^_^Creating named tuples The named tuple class namedTuples in the Python collection gives meaning to each position in the tuple and enhances the readability of the code Sexual and descriptive. They can be used anywhere regular tuples are used, and add the ability to access fields by name rather than positional index. It comes from the Python built-in module collections. The general syntax used is: import collections XxNamedT

All data are automatically assigned a "DOB" (Date of Birth) at the beginning. Therefore, it is inevitable to encounter date and time data when processing data at some point. This tutorial will take you through the datetime module in Python and using some peripheral libraries such as pandas and pytz. In Python, anything related to date and time is handled by the datetime module, which further divides the module into 5 different classes. Classes are simply data types that correspond to objects. The following figure summarizes the 5 datetime classes in Python along with commonly used attributes and examples. 3 useful snippets 1. Convert string to datetime format, maybe using datet

Hello, my name is somenzz, you can call me Brother Zheng. Python's import is very intuitive, but even so, sometimes you will find that even though the package is there, we will still encounter ModuleNotFoundError. Obviously the relative path is very correct, but the error ImportError:attemptedrelativeimportwithnoknownparentpackage imports a module in the same directory and a different one. The modules of the directory are completely different. This article helps you easily handle the import by analyzing some problems often encountered when using import. Based on this, you can easily create attributes.

In CTR estimation, the mainstream method uses feature embedding+MLP, in which features are very critical. However, for the same features, the representation is the same in different samples. This way of inputting to the downstream model will limit the expressive ability of the model. In order to solve this problem, a series of related work has been proposed in the field of CTR estimation, which is called feature enhancement module. The feature enhancement module corrects the output results of the embedding layer based on different samples to adapt to the feature representation of different samples and improve the expression ability of the model. Recently, Fudan University and Microsoft Research Asia jointly published a review on feature enhancement work, comparing the implementation methods and effects of different feature enhancement modules. Now, let us introduce a

The working principle of Ansible can be understood from the above figure: the management end supports three methods of local, ssh, and zeromq to connect to the managed end. The default is to use the ssh-based connection. This part corresponds to the connection module in the above architecture diagram; you can press the application type HostInventory (host list) classification is carried out in other ways. The management node implements corresponding operations through various modules. A single module and batch execution of a single command can be called ad-hoc; the management node can implement a collection of multiple tasks through playbooks. Implement a type of functions, such as installation and deployment of web services, batch backup of database servers, etc. We can simply understand playbooks as, the system passes
