所谓模块(module)其实就是在函数/变量名字前加前缀的一种方式。这样1)便于组织和重用相同功能的代码2)避免函数名和变量名的冲突。

1. 模块中定义的变量

- __name__:如果该模块被执行(python moduleName.py),那么__name__=='__main__';如果模块被import,那么__name__=='__moduleName__'。
- __author__:定义作者名字
- dir(moduleName)输出模块中的变量和函数

2. 模块中变量的作用域

- 和类中变量命名相似。python没有去限制private函数或是变量的引用,但是我们一般要自行的去遵循常见的python命名规则。

3. 第三方模块的安装和使用

- 使用pip/pip3来安装(当然还有其他方法)
- 模块的搜索路径:sys.path/sys.path.append('own_path');设置PYTHONPATH

4. 常用内置模块

- datetime (import datetime)
    object
        timedelta
        tzinfo
            timezone
        time
        date
            datetime
- collections (import collections)
    - namedtuple:可以按属性引用`p = namedtuple('Point', ['x', 'y']); p = Point(1, 2); print(p.x, p.y)`
    - deque:双向的插入和删除`q = deque(['a', 'b', 'c']); q.appendleft('d')`
    - defaultdict:key不存在的时候返回默认值,而不是抛出KeyError错误。`dd = defaultdict(lambda: 'N/A'); dd['key1']='abc'; dd['key1']=>'abc'; dd['key2']=>'N/A'`
    - OrderedDict:key是有序的
    - Counter:简单的计数器,是dict的子类
- base64 (import base64)
    - 任意二进制到文本字符串的编码方法
    - 3字节转成4个6bit组,然后查表得到转换之后对应的字符
    - 不同的条件下,文本字符串集合会有一些差别
- struct:import struct
    - pack/unpack
    - 参数处理指令:big-endian/little-edian, IH...
- hashlib:import hashlib
    - md5
- itertools:import itertools
    - itertools用于操作壳迭代对象
    - count()/cycle()/repeat()
    - chain()/groupby()
- contextlib:import contextlib
    - 上下文管理器,预处理(pre)和后处理(post)
    - 实现__enter__和__exit__两个方法来实现上下文管理
    - @contextmanager配合yield
    - closing方法实现自动资源回收

In [8]:
import os
dir(os)

print(os.__name__)
#print(os.__all__)


os

In [22]:
import datetime
from datetime import timedelta
print(datetime.MINYEAR)
print(datetime.MAXYEAR)
print(dir(datetime.date))
print(timedelta(microseconds=-1)) ## normalization的结果
print(timedelta.min, timedelta.max, timedelta.resolution)

print('====================================================')
year = timedelta(days=365)
another_year = timedelta(weeks=40, days=84, hours=23, minutes=50, seconds=60)
print(year.total_seconds())
print(year == another_year)
print(year * 10)
print(year - another_year)
print(year / another_year)


1
9999
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year']
-1 day, 23:59:59.999999
-999999999 days, 0:00:00 999999999 days, 23:59:59.999999 0:00:00.000001
====================================================
31536000.0
False
3650 days, 0:00:00
0:09:00
1.0000171235808832

In [28]:
from datetime import date
print(date.today())
d = date.today()
print(d.toordinal())
print(d.weekday())
print(d.isoweekday())
print(d.isocalendar())
print(d.timetuple())
print((d.year, d.month, d.day))
print(d.isoformat())


2017-06-25
736505
6
7
(2017, 25, 7)
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=176, tm_isdst=-1)
(2017, 6, 25)
2017-06-25

In [41]:
from datetime import datetime
from datetime import date
from datetime import time

print(datetime.utcnow())
print(datetime.combine(date.today(), time(12, 30)))
print(datetime.utcnow().timetuple())
print(datetime.utcnow().isocalendar())


2017-06-25 08:53:06.775299
2017-06-25 12:30:00
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=25, tm_hour=8, tm_min=53, tm_sec=6, tm_wday=6, tm_yday=176, tm_isdst=-1)
(2017, 25, 7)

In [6]:
import collections

Point3D = collections.namedtuple('Point', ['x', 'y', 'z'])
p3 = Point3D(1, 2 ,3)
print(p3)


Point(x=1, y=2, z=3)

In [8]:
import base64

s = b'Hello, Longshan!'
base64.b64encode(s)


Out[8]:
b'SGVsbG8sIExvbmdzaGFuIQ=='

In [10]:
import struct

struct.pack('>I', 10240099)
s = b'\x42\x4d\x38\x8c\x0a\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00\x80\x02\x00\x00\x68\x01\x00\x00\x01\x00\x18\x00'
struct.unpack('<ccIIIIIIHH', s)


Out[10]:
(b'B', b'M', 691256, 0, 54, 40, 640, 360, 1, 24)

In [13]:
import hashlib

m = hashlib.md5('Hello, Longhshan'.encode('utf-8'))
print(m.hexdigest())


1f76714a20b6c8a644df1a161694830d

In [17]:
import itertools

naturals = itertools.count(1)
for num in naturals:
    #print(num)
    if num > 100:
        break
        
        
dict(itertools.groupby('1234111234'))


Out[17]:
{'1': <itertools._grouper at 0x105c0c400>,
 '2': <itertools._grouper at 0x105b59da0>,
 '3': <itertools._grouper at 0x105b59ef0>,
 '4': <itertools._grouper at 0x105b59e80>}

In [19]:
from contextlib import contextmanager

class Query(object):
    def __init__(self, name):
        self.name = name
    def query(self):
        print('QUery info about %s...' %self.name)
        
@contextmanager
def create_query(name):
    print('Begin')
    q = Query(name)
    yield q
    print('End')
    
with create_query('Longshan') as q:
    q.query()
    
@contextmanager
def tag(name):
    print('<%s>' %name)
    yield
    print('</%s>' %name)
with tag('H1'):
    print('Hello')
    print('World')


Begin
QUery info about Longshan...
End
<H1>
Hello
World
</H1>

In [ ]: