Python Common Module Learning

Source: Internet
Author: User

First, what is the module

The modules in Python are pieces of code that can be divided into multiple, organized, independent, but interacting snippets of code, and these self-contained, organized snippets of code are modules. Python allows the "import" of other modules for code reuse, which also enables the organization of separate code files into larger program systems. In Python, a module is also an object. All variables defined at the top level of a module are imported as properties of the module being imported.

Second, the use of the module

1. Python Program architecture
A Python program typically consists of a top-level program file and several module files. The top-level file contains the main control flow of the program, the module file is to provide a variety of functional components for the top-level files or other modules, when the module first import (or reload), Python will immediately execute the module file of the top-level program code (not within the function code), The code inside the function body is not executed until the function is called.
2, the implementation of the module environment
Modules are imported, but modules can also be imported and used in other modules, which can be written in Python or other programming languages
Modules can contain variables, functions, and classes to do their work, and functions and classes can include variables and other elements
3. Import Module
Only module names can be used when importing modules, not module filenames with. PY Suffixes

import语句:            导入指定的整个模块,包括生成一个以模块名命名的名称空间            import module1[,module2[,...moduleN]]            建议一个import语句只导入一个模块            import module as module_aliasfrom-import语句:            常用于只导入指定模块的部分属性至当前名称空间            from module import name1[,name2[,...nameN]]          import和from-import是赋值语句            import和from是可执行语句,类似于def,因此,它们可以嵌套在if测试中,出现于def中等等            Python执行到这些语句时才会对其进行解析,这意味着,所有来自模块的属性仅在import语句执行后才能使用模块就是名称空间            模块的名称空间可以通过属性__dict__或dir(M)获取                模块属性可通过点号(.)运算符获取,格式为M.attr            模块是一个独立的作用域(本地变量就是全局变量)

4, import of the working mechanism
Import statement performs three steps when importing a specified module
1. Find the module file
Search for module files under the specified path (sys.path)
2, compiled into byte code
The file is compiled when it is imported, so the. PYc bytecode file for the top-level file is discarded after internal use, and only the files that are imported are left. pyc file
3. Execute the code of the module to create the object it defines
All statements in the module file are executed sequentially, from beginning to end, and any assignment to the variable name in this step produces the properties of the resulting module file
Note: The module does not perform the previous step only on the first import, and subsequent import operations are simply extracting the loaded module objects in memory, reload () can be used to reload the module

Three, time

The

Time module is used to manipulate time values
Timestamp: time.time ()
Formatted time: string representation, Time.strftime ('%y-%m-%d ')
Structured time: tuple representation, time.localtime (), Time.gmtime ()

Asctime: Return time format Sun Mar 10:51:28 2018In [1]: Import Timein [2]: Time.asctime () out[2]: ' Sun Mar 10:51:28 2018 ' in [3]: t Ime.asctime (Time.localtime ()) out[3]: ' Sun Mar 10:51:45 2018 ' CTime: A string that converts the time since era to local time in seconds, equivalent to Time.asctime ( Time.localtime ()) in [4]: Time.ctime () out[4]: ' Sun Mar 10:55:26 2018 ' Gmtime: current UTC time in [7]: Time.gmtime () out[7]: Time.struct_time (tm_year=2018, tm_mon=3, tm_mday=18, tm_hour=2, tm_min=58, Tm_sec=1, tm_wday=6, tm_yday=77, tm_isdst=0 ) LocalTime: Return local time in [9]: Time.localtime () out[9]: Time.struct_time (tm_year=2018, tm_mon=3, tm_mday=18, tm_hour=11, tm_ Min=3, tm_sec=56, tm_wday=6, tm_yday=77, tm_isdst=0) Strptime: Convert the time passed in to STR format in [all]: Time.strptime (' 2018-3-18 ', '% y-%m-%d ') out[11]: Time.struct_time (tm_year=2018, tm_mon=3, tm_mday=18, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_ yday=77, Tm_isdst=-1) strftime: Convert the struct format time to the specified format in []: Time.strftime ('%y-%m-%d ') out[13]: ' 2018-03-18 ' in [14]: Time.strftime ("%y-%m-%d%h:%m:%s", Time.gmtime ()) out[14]: ' 2018-03-18 03: 09:47 ' mktime: Convert the struct time to timestamp in []: Time.mktime (time.strptime (' 2018-3-18 ', '%y-%m-%d ')) out[15]: 1521302400.0sleep: Sleep time in [+]: Time.sleep (5)

DateTime Module for operating time
Datetime.date: A class that represents a date. Common attributes are year, month, day
Datetime.time: A class that represents time. Common properties are hour, minute, second, microsecond
Datetime.datetime: Represents the date time
Datetime.timedelta: Represents a time interval, that is, the length between two points in time
Timedelta ([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, Weeks]] []]
Strftime ("%y-%m-%d")

>>> import datetime                         >>> import time#当前时间>>> print(datetime.datetime.now())2018-03-18 12:10:27.199643#格式化时间戳>>> print(datetime.date.fromtimestamp(time.time()))2018-03-18#当前时间?3天>>> print(datetime.datetime.now() + datetime.timedelta(3))2018-03-21 12:10:52.869598#当前时间?3天>>> print(datetime.datetime.now() + datetime.timedelta(-3))2018-03-15 12:11:04.721491#当前时间?3小时>>> print(datetime.datetime.now() + datetime.timedelta(hours=3))2018-03-18 15:11:18.628036#当前时间?4小时>>> print(datetime.datetime.now() + datetime.timedelta(hours=-4))2018-03-18 08:11:42.096182#当前时间?120分钟>>> print(datetime.datetime.now() + datetime.timedelta(minutes=120))2018-03-18 14:11:53.305800
Iv. Random

Random number

In [1]: import randomIn [2]: random.random()Out[2]: 0.9381887159573181#随机返回1到10之间的整数In [3]: random.randint(1,10)Out[3]: 8#从1到10中,2为步长随机返回一个数In [4]: random.randrange(1,10,2)Out[4]: 5#随机返回序列中的元素In [5]: random.choice([1,2,3,4])Out[5]: 3#打乱序列中的元素顺序In [10]: l1 = [1,2,3,4]In [11]: random.shuffle(l1)In [12]: l1Out[12]: [1, 2, 4, 3]#随机返回序列中的2个元素In [13]: random.sample(l1,2)Out[13]: [2, 4]

Python Common Module Learning

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.