所谓模块(module)其实就是在函数/变量名字前加前缀的一种方式。这样1)便于组织和重用相同功能的代码2)避免函数名和变量名的冲突。
- __name__:如果该模块被执行(python moduleName.py),那么__name__=='__main__';如果模块被import,那么__name__=='__moduleName__'。
- __author__:定义作者名字
- dir(moduleName)输出模块中的变量和函数
- 和类中变量命名相似。python没有去限制private函数或是变量的引用,但是我们一般要自行的去遵循常见的python命名规则。
- 使用pip/pip3来安装(当然还有其他方法)
- 模块的搜索路径:sys.path/sys.path.append('own_path');设置PYTHONPATH
- 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__)
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)
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())
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())
In [6]:
import collections
Point3D = collections.namedtuple('Point', ['x', 'y', 'z'])
p3 = Point3D(1, 2 ,3)
print(p3)
In [8]:
import base64
s = b'Hello, Longshan!'
base64.b64encode(s)
Out[8]:
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]:
In [13]:
import hashlib
m = hashlib.md5('Hello, Longhshan'.encode('utf-8'))
print(m.hexdigest())
In [17]:
import itertools
naturals = itertools.count(1)
for num in naturals:
#print(num)
if num > 100:
break
dict(itertools.groupby('1234111234'))
Out[17]:
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')
In [ ]: