Python3基础杂记

Python

一、语言

1.编译型语言

编译器把源程序的每一条语句都编译成机器语言,并保存成二进制文件,运行时计算机可以直接以机器语言来运行程序,速度快。

  • 优点:编译器一般会有预编译的过程对代码进行优化。只编译一次,运行时不需要编译,编译型语言的程序执行效率高,可脱离语言环境独立运行。
  • 缺点:编译之后如果需要修改就需要整个模块重新编译,编译的时候根据对应的运行环境生成机器码,不同的操作系统之间的移植存在问题,需要根据运行的操作系统环境编译不同的可执行文件。

2.解释型语言

解释器在执行程序时,将一条一条的语句解释成机器语言给计算机执行,运行速度不如编译后的程序运行快。

  • 优点:良好的跨平台和兼容性,修改代码的时候直接修改就可以,可以快速部署,不用停机维护。
  • 缺点:每次运行的时候都要解释一遍,性能上不如编译型语言。

3.静态语言

数据类型是在运行前(如编译阶段)检查的,也就是说在写程序时要声明所有变量的数据类型。

4.动态语言

运行阶段检查数据类型,也就是说在写程序时不用给任何变量指定数据类型,该语言会在你第一次赋值给变量时,在内部将数据类型记录下来。

5.强类型语言

强制数据类型定义的语言。一旦一个变量被指定了某个数据类型,如果不经过强制转换,那么它就永远是这个数据类型。强类型定义语言是类型安全的语言。

6.弱类型语言

数据类型可以被忽略的语言。它与强类型定义语言相反, 一个变量可以赋不同数据类型的值。弱类型定义语言是类型不安全的语言。

知乎:弱类型、强类型、动态类型、静态类型语言的区别是什么?

二、基本数据类型

  • 不可变数据类型(可哈希):numstrtuple(、bool)
  • 可变数据类型(不可哈希):listdictset
  • tuple子元素不可更改,若子元素为可变数据类型,则可更改子元素
  • dict[key] 必须是不可变数据类型
  • set为可变数据类型,但其子元素为不可变数据类型。不可变集合frozenset([iterable])

1.增

  • list –> append(object)insert(index, object)extend(iterable)(add every element from the iterable)
  • dict –> dict[key] = value、setdefault(k[,d])fromkeys(iterable, value)
  • set –> add(element)update(iterable)(add every element from the iterable)

2.删

1
2
3
4
5
6
7
8
9
10
11
# del关键字
>>> a = 1
>>> b = a
>>> c = a
>>> del a, b
>>> print(a)
NameError: name 'a' is not defined
>>> print(b)
NameError: name 'b' is not defined
>>>print(c)
1
  • list –> pop([index=-1])remove(object)clear()del listdel list[x:y:z]
  • dict –> pop(k[,d])popitem()clear()del dictdel dict[key]
  • set –> pop()(arbitrary)remove(element)(raise a KeyError if the element is not a member)、discard(element)(do nothing if the element is not a member)、clear()del set

3.改

  • list –> list[x:y:z] = value
  • dict –> update(dict)

4.查

  • 索引切片
  • for
  • str –> find(sub[, start[, end]])(return the lowest index in substring else return -1)、index(sub[, start[, end]])(return the lowest index in substring else raise ValueError)
  • list –> index(value, [start, [stop]])
  • dict –> keys()values()items()get(k[, d=None])
  • set –> 交集(&intersection())、并集(|union())、差集(-difference())、反交集(^symmetric_difference())、子集(issubset())、超集(issuperset())
    (列表元素去重 —> list => set)
1
2
3
4
5
# 交集(&、intersection())
>>> set1 = {1, 2, 3, 4, 5}
>>> set2 = {4, 5, 6, 7, 8}
>>> print(set1 & set2, set1.intersection(set2))
{4, 5} {4, 5}
1
2
3
4
5
# 并集(|、union())
>>> set1 = {1, 2, 3, 4, 5}
>>> set2 = {4, 5, 6, 7, 8}
>>> print(set1 | set2, set1.union(set2))
{1, 2, 3, 4, 5, 6, 7, 8} {1, 2, 3, 4, 5, 6, 7, 8}
1
2
3
4
5
6
7
# 差集(-、difference())
>>> set1 = {1, 2, 3, 4, 5}
>>> set2 = {4, 5, 6, 7, 8}
>>> print(set1 - set2, set1.difference(set2))
{1, 2, 3} {1, 2, 3}
>>> print(set2 - set1, set2.difference(set1))
{8, 6, 7} {8, 6, 7}
1
2
3
4
5
# 反交集(^、symmetric_difference())
>>> set1 = {1, 2, 3, 4, 5}
>>> set2 = {4, 5, 6, 7, 8}
>>> print(set1 ^ set2, set1.symmetric_difference(set2))
{1, 2, 3, 6, 7, 8} {1, 2, 3, 6, 7, 8}
1
2
3
4
5
6
7
# 超集(issuperset())、子集(issubset())
>>> set1 = {1, 2, 3, 4, 5}
>>> set2 = {1, 2, 3, 4, 5, 6, 7, 8}
>>> print(set1 < set2, set1.issubset(set2))
True True
>>> print(set2 > set1, set2.issuperset(set1))
True True

5.运算符及优先级

逻辑运算符

逻辑运算符逻辑表达式描述
notnot xx -> True = False else True
andx and yx -> True = y else = x
orx or yx -> True = x else = y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# bool为True或False的情况

# True:

>>> print(bool(1)) # 整数1
>>> print(bool('a')) # 非空字符串
>>> print(bool(' ')) # 空白字符
>>> print(bool(" ")) # 空白字符
>>> print(bool(['a'])) # 非空列表
>>> print(bool({1})) # 非空集合
>>> print(bool((1))) # 非空元组
>>> print(True) # True
>>> print(not None) # 非None
>>> print(not False) # 非假
>>> print(1 is 1) # is
>>> print(1 > 0) # 比较
>>> print(1 < 2) # 比较
>>> print(2 == 2) # 比较
>>> print(True == 1) # 比较
>>> print(False == 0) # 比较
......

# False:

>>> print(bool(0)) # 整数0
>>> print(bool(0.0)) # 浮点数
>>> print(bool(0.0j)) # 复数
>>> print(bool(0.0 + 0.0j)) # 复数
>>> print(bool()) # 空
>>> print(bool('')) # 空字符
>>> print(bool("")) # 空字符
>>> print(bool([])) # 空列表
>>> print(bool({})) # 空集合
>>> print(bool(())) # 空元组
>>> print(bool(None)) # None
>>> print(False) # False
>>> print(not True) # 非真
>>> print(not 1) # 非真
>>> print(1 is 2) # is
>>> print(1 > 2) # 比较
>>> print(2 < 1) # 比较
>>> print(2 == 1) # 比较
>>> print(True == 0) # 比较
>>> print(False == 1) # 比较
>>> print(None == 0) # 比较
>>> print(None == 1) # 比较
>>> print(None == '') # 比较
......
1
2
3
4
5
6
7
8
# 非 not x
x -> True = False else True

>>> print(not 1)
False

>>> print(not 0)
True
1
2
3
4
5
6
7
8
# 与 x and y
x -> True = y else = x

>>> print(1 and 2)
2

>>> print(0 and 2)
0
1
2
3
4
5
6
7
8
# 或 x or y
x -> True = x else = y

>>> print(1 or 2)
1

>>> print(0 or 2)
2

优先级

运算符优先级(高->低)描述
()、[]()显示设置、[]下标索引
~按位取反
*、/、%、//乘、除、取余、整除
+、-加减
>>、<<右移、左移
&按位与
^、|按位异或、按位或
<=、<、>、>=比较运算符
<>、==、!=等于运算符
=、%=、/=、//=、-=、+=、*=、**=赋值运算符
is、is not身份运算符
in、not in成员运算符
and、or、not逻辑运算符
if else条件表达式
lambdalambda表达式

6.else语句

如果while循环中存在else代码块,它将总是被执行,除非通过break语句来中断这一循环(此时不会执行else语句块)。
对于for循环,else部分同样是可选的,当循环中包含else时,总会在for循环结束后开始执行,除非遇到了break语句(此时不会执行else语句块)。
try…except…else,else语句在未发生异常时执行。
with语句会获取由open语句返回的对象,并在代码块开始之前调用__enter__,在代码块执行完之后调用__exit__
assert(断言)用来判断其后一句的正确与否,若错误,则抛出AssertionError

7.深浅拷贝

  • is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 赋值运算:指向同一个内存地址,完全一样。

>>> list1 = ['x', 'y', 'z']
>>> list2 = list1
>>> print(list1, list2)
['x', 'y', 'z'] ['x', 'y', 'z']
>>> print(list1 is list2) # 指向同一个内存地址
True
>>> print(id(list1) == id(list2)) # 指向同一个内存地址
True
>>> list1.pop()
>>> print(list1, list2)
['x', 'y'] ['x', 'y']
>>> print(list1 is list2) # 被修改后,仍指向同一个内存地址
True
>>> print(id(list1) == id(list2)) # 被修改后,仍指向同一个内存地址
True

>>> list1 = [['x', 'p'], 'y', 'z']
>>> list2 = list1
>>> print(list1, list2)
[['x', 'p'], 'y', 'z'] [['x', 'p'], 'y', 'z']
>>> print(list1 is list2) # 指向同一个内存地址
True
>>> print(id(list1) == id(list2)) # 指向同一个内存地址
True
>>> list1[0].pop()
>>> print(list1, list2)
[['x'], 'y', 'z'] [['x'], 'y', 'z']
>>> print(list1 is list2) # 被修改后,仍指向同一个内存地址
True
>>> print(id(list1) == id(list2)) # 被修改后,仍指向同一个内存地址
True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 浅拷贝:在内存中重新创建了一个空间存放新列表,新列表中的元素与原列表中的元素是公用的。

>>> list1 = ['x', 'y', 'z']
>>> list2 = list1.copy()
>>> print(list1, list2)
['x', 'y', 'z'] ['x', 'y', 'z']
>>> print(list1 is list2) # 重新创建空间存放新列表
False
>>> print(id(list1) == id(list2)) # 重新创建空间存放新列表
False
>>> print(list1[0] is list2[0]) # 新列表中的元素与原列表中的元素是公用的
True
>>> print(id(list1[0]) == id(list2[0])) # 新列表中的元素与原列表中的元素是公用的
True
>>> list1.pop()
>>> print(list1, list2)
['x', 'y'] ['x', 'y', 'z']
>>> print(list1 is list2) # 重新创建空间存放新列表,并且被修改
False
>>> print(id(list1) == id(list2)) # 重新创建空间存放新列表,并且被修改
False
>>> print(list1[0] is list2[0]) # 新列表中的元素与原列表中的元素是公用的
True
>>> print(id(list1[0]) == id(list2[0])) # 新列表中的元素与原列表中的元素是公用的
True

>>> list1 = [['x', 'p', 'q'], 'y', 'z']
>>> list2 = list1.copy()
>>> print(list1, list2)
[['x', 'p', 'q'], 'y', 'z'] [['x', 'p', 'q'], 'y', 'z']
>>> print(list1 is list2) # 重新创建空间存放新列表
False
>>> print(id(list1) == id(list2)) # 重新创建空间存放新列表
False
>>> print(list1[0] is list2[0]) # 新列表中的元素与原列表中的元素是公用的
True
>>> print(id(list1[0]) == id(list2[0])) # 新列表中的元素与原列表中的元素是公用的
True
>>> print(list1[0][0] is list2[0][0]) # 新列表中的元素与原列表中的元素是公用的
True
>>> print(id(list1[0][0]) == id(list2[0][0])) # 新列表中的元素与原列表中的元素是公用的
True
>>> list1[0].pop()
>>> print(list1, list2)
[['x', 'p'], 'y', 'z'] [['x', 'p'], 'y', 'z']
>>> print(list1 is list2) # 重新创建空间存放新列表,并且被修改
False
>>> print(id(list1) == id(list2)) # 重新创建空间存放新列表,并且被修改
False
>>> print(list1[0] is list2[0]) # 新列表中的元素与原列表中的元素是公用的
True
>>> print(id(list1[0]) == id(list2[0])) # 新列表中的元素与原列表中的元素是公用的
True
>>> print(list1[0][0] is list2[0][0]) # 新列表中的元素与原列表中的元素是公用的
True
>>> print(id(list1[0][0]) == id(list2[0][0])) # 新列表中的元素与原列表中的元素是公用的
True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 深拷贝:列表是在内存中重新创建,列表中可变的数据类型是重新创建的,列表中的不可变的数据类型是公用的。

>>> import copy
>>> list1 = [['x', 'p'], 'y', 'z']
>>> list2 = copy.deepcopy(list1)
>>> print(list1, list2)
[['x', 'p'], 'y', 'z'] [['x', 'p'], 'y', 'z']
>>> print(list1 is list2) # 列表重新创建
False
>>> print(id(list1) == id(list2)) # 列表重新创建
False
>>> print(list1[0] is list2[0]) # 列表中可变的数据类型(列表)重新创建
False
>>> print(id(list1[0]) == id(list2[0])) # 列表中可变的数据类型(列表)重新创建
False
>>> print(list1[1] is list2[1]) # 列表中不可变的数据类型(字符串)公用
True
>>> print(id(list1[1]) == id(list2[1])) # 列表中可变的数据类型(字符串)公用
True
list2[0].pop()
>>> print(list1, list2)
[['x', 'p'], 'y', 'z'] [['x'], 'y', 'z']
>>> print(list1 is list2)
False
>>> print(id(list1) == id(list2)) # 列表重新创建,并且被修改
False
>>> print(list1[0] is list2[0]) # 列表中可变的数据类型(列表)重新创建,并且被修改
False
>>> print(id(list1[0]) == id(list2[0])) # 列表中可变的数据类型(列表)重新创建,并且被修改
False
>>> print(list1[1] is list2[1]) # 列表中可变的数据类型(字符串)公用
True
>>> print(id(list1[1]) == id(list2[1])) # 列表中可变的数据类型(字符串)公用
True

8.转换

str —> bytes
str.encode()

1
2
3
4
5
6
>>> str1 = '你好'
>>> bytes1 = str1.encode('utf-8')
>>> print(str1, type(str1))
你好 <class 'str'>
>>> print(bytes1, type(bytes1))
b'\xe4\xbd\xa0\xe5\xa5\xbd' <class 'bytes'>

bytes —> str
bytes.decode()

1
2
3
4
5
6
>>> str1 = b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> bytes1 = str1.decode('utf-8')
>>> print(str1, type(str1))
b'\xe4\xbd\xa0\xe5\xa5\xbd' <class 'bytes'>
>>> print(bytes1, type(bytes1))
你好 <class 'str'>

str —> list
str.split()

1
2
3
>>> str1 = 'abcdefg'
>>> print(str1.split(' '))
['abcdefg']

list —> str
“”.join(list)

1
2
3
>>> list1 = ['abcde', 'fg']
>>> print("".join(list1))
abcdefg

dict —> json
json.dumps()
json.dump()

1
2
3
4
5
6
7
8
>>> list_1 = [{"name": "张三", "age": 20}, {"name": "李四", "age": 18}]
>>> data_json = json.dumps(list_1)

>>> # dict list 写入文件
>>> list_2 = [{"name": "张三", "age": 20}, {"name": "李四", "age": 18}]
>>> fp = open('new.json', 'w')
>>> json.dump(list_2, fp)
>>> fp.close()

json —> dict
json.loads()
json.load()

1
2
3
4
5
6
>>> data = '[{"name":"张三","age":20},{"name":"李四","age":18}]'
>>> list_data = json.loads(data)

>>> # 读取json文件
>>> fp = open('new.json', 'r')
>>> resulst = json.load(fp)

json —> csv

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> import json
>>> import csv
>>> # 1.分别 读 , 创建文件
>>> json_fp = open('douban.json', 'r', encoding='utf-8')
>>> csv_fp = open('douban.csv', 'w', encoding='utf-8', newline='')
>>> # 2.提出 表头 , 表内容
>>> data_list = json.load(json_fp)
>>> sheet_title = data_list[0].keys()
>>> print(sheet_title)
>>> sheet_data = []
>>> for data in data_list:
>>> sheet_data.append(data.values())
>>> # 3. csv 写入器
>>> writer = csv.writer(csv_fp)
>>> # 4. 写入表头
>>> writer.writerow(sheet_title)
>>> # 5. 写入内容
>>> writer.writerows(sheet_data)
>>> # 6. 关闭两个文件
>>> json_fp.close()
>>> csv_fp.close()

9.序列化和反序列化

变量从内存中变成可存储或传输的过程称之为序列化。把变量内容从序列化的对象重新读到内存称之为反序列化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# pickle
# dumps、loads、dump、load

>>> import pickle
>>> d = dict(name='Bob', age=20, score=88)
>>> print(pickle.dumps(d))
b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x03\x00\x00\x00Bobq\x02X\x03\x00\x00\x00ageq\x03K\x14X\x05\x00\x00\x00scoreq\x04KXu.'
>>> print(pickle.loads(pickle.dumps(d)))
{'name': 'Bob', 'age': 20, 'score': 88}

>>> with open('dump.txt', 'wb') as f:
>>> pickle.dump(d, f)

>>> with open('dump.txt', 'rb') as f:
>>> pickle.load(f)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# json
# dumps、loads、dump、load

>>> import json
>>> d = dict(name='Bob', age=20, score=88)
>>> json.dumps(d)
'{"age": 20, "score": 88, "name": "Bob"}'

>>> json_str = '{"age": 20, "score": 88, "name": "Bob"}'
>>> json.loads(json_str)
{'age': 20, 'score': 88, 'name': 'Bob'}

>>> import json
>>> dic = {'key': 'value'}
>>> with open('json_file', 'w') as f:
>>> json.dump(dic, f)
>>> with open('json_file') as f:
>>> dic2 = json.load(f)
>>> print(type(dic2), dic2)
<class 'dict'> {'key': 'value'}

# ensure_ascii参数

>>> import json
>>> dic = {'你': '我'}
>>> with open('file', 'w', encoding='utf-8') as f:
>>> json.dump(dic, f)
>>> ret = json.dumps(dic)
>>> f.write(ret + '\n')
>>> json.dump(dic, f, ensure_ascii=False)
>>> ret = json.dumps(dic, ensure_ascii=False)
>>> f.write(ret + '\n')
{"\u4f60": "\u6211"}{"\u4f60": "\u6211"}
{"你": "我"}{"你": "我"}


# json格式化(pprint打印)

>>> import json
>>> data = {'username': '张三', 'sex': 'male', 'age': 19, 'address': {'省份': '广东', '学校': '深圳大学'}}
>>> json_data = json.dumps(data, sort_keys=True, indent=2, separators=(',', ':'), ensure_ascii=False)
>>> print(json_data)
{
"address":{
"学校":"深圳大学",
"省份":"广东"
},
"age":19,
"sex":"male",
"username":"张三"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# shelve
A "shelf" is a persistent, dictionary-like object. The difference
with dbm databases is that the values (not the keys!) in a shelf can
be essentially arbitrary Python objects -- anything that the "pickle"
module can handle. This includes most class instances, recursive data
types, and objects containing lots of shared sub-objects. The keys
are ordinary strings.


>>> import shelve
>>> f = shelve.open('shelve_file', writeback=True)
>>> f['key1'] = 'abc'
>>> f['key2'] = ('a', 'b', 'c')
>>> f['key3'] = ['12', 34, (5, 6), [7, 8]]
>>> f['key4'] = {'int': 10, 'float': 9.5, 'string': 'Sample data'}
>>> print(f['key1']) #key不存在报错
>>> print(f['key2'])
>>> print(f['key3'])
>>> print(f['key4'])
>>> f['key3'].append('hello')
>>> f['key4']['bool'] = True
>>> print(f['key3'])
>>> print(f['key4'])
>>> f.close()
abc
('a', 'b', 'c')
['12', 34, (5, 6), [7, 8]]
{'int': 10, 'float': 9.5, 'string': 'Sample data'}
['12', 34, (5, 6), [7, 8], 'hello']
{'int': 10, 'float': 9.5, 'string': 'Sample data', 'bool': True}

10.编码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 一些典型编码


# latin1(即 iso8859_1)
一种重要的编码,是其他编码的基础,例如 cp1252 和Unicode(注意,latin1 与 cp1252 的字节值是一样的,甚至连码位也相同)。

# cp1252
Microsoft 制定的 latin1 超集,添加了有用的符号,例如弯引号和€(欧元);有些 Windows 应用把它称为“ANSI”,但它并不是 ANSI 标准。

# cp437
IBM PC 最初的字符集,包含框图符号。与后来出现的 latin1 不兼容。

# gb2312
用于编码简体中文的陈旧标准;这是亚洲语言中使用较广泛的多字节编码之一。

# utf-8
目前 Web 中最常见的 8 位编码; 与 ASCII 兼容(纯 ASCII 文本是有效的 UTF-8 文本)。

# utf-16le
UTF-16 的 16 位编码方案的一种形式;所有 UTF-16 支持通过转义序列(称为“代理对”,surrogate pair)表示超过 U+FFFF 的码位。
  • 文件的储存、传输不能是Unicode(只能是ASCII,UTF-8,GBK…..)
  • Python2默认编码ASCII,Python3默认编码UTF-8
  • Python3中字符串str用Unicode编码
1
2
3
4
# ASCII

大、小写字母,数字0-9、标点符号及特殊字符
一个英文字符(如A): 01000001 8bit/1byte
1
2
3
4
# Unicode

一个英文字符(如A): 00000000 00000001 0000001 01000001 32bit/4byte
一个中文字符(如中):00000000 00000001 0000001 01000011 32bit/4byte
1
2
3
4
# UTF-8

一个英文字符(如A): 01000001 8bit/1byte
一个中文字符(如中):00000001 0000001 01000011 24bit/3byte
1
2
3
4
# GBK

一个英文字符(如A): 01000001 8bit/1byte
一个中文字符(如中):0000001 01000011 16bit/2byte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 对于英文

str:
表现形式:s = 'test'
编码方式:01001010 (Unicode)
bytes:
表现形式:s = b'test'
编码方式:01110101 (UTF-8,GBK......)

>>> 'test'.encode('UTF-8')
b'test'

>>> 'test'.encode('GBK')
b'test'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 对于中文

str:
表现形式:s = '中文'
编码方式:01101010 (Unicode)
bytes:
表现形式:s = b'\xe4\xb8\xad\xe6\x96\x87'(UTF-8)
b'\xd6\xd0\xce\xc4'(GBK)
编码方式:01011110 (UTF-8,GBK......)

>>> '中文'.encode('UTF-8')
b'\xe4\xb8\xad\xe6\x96\x87'

>>> '中文'.encode('GBK')
b'\xd6\xd0\xce\xc4'

三、函数

1.函数传参顺序

def func(位置参数, 可变参数*args, 默认参数, 关键字参数**kwargs): pass

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> def parameter(name, age, *args, sex='男', no='12', **kwargs):
>>> print('name:', name)
>>> print('age:', age)
>>> print('sex:', sex)
>>> print('no:', no)
>>> print('args:', args)
>>> print('kwargs:', kwargs)
>>> parameter('Conyyon', 21, '大学', 'English', behavior='说话', hobby='Coding')
name: Conyyon
age: 21
sex:
no: 12
args: ('大学', 'English')
kwargs: {'behavior': '说话', 'hobby': 'Coding'}
>>> parameter('Conyyon', 21, '大学', 'English', sex='女', behavior='说话', hobby='Coding', no='20')
name: Conyyon
age: 21
sex:
no: 20
args: ('大学', 'English')
kwargs: {'behavior': '说话', 'hobby': 'Coding'}

若函数默认参数的值是可变数据类型,则每次调用函数时,默认参数如果不传值就会公用这个数据类型

1
2
3
4
5
6
7
8
9
>>> def func(k, l={}): #Pycharm提示'Default argument value is mutable'
>>> l[k] = k
>>> print(l)
>>> func(1)
{1: 1}
>>> func(2)
{1: 1, 2: 2}
>>> func(3)
{1: 1, 2: 2, 3: 3}

2.函数名

函数名就是内存地址,可以赋值,可以作为容器类型的元素,可以作为函数的返回值,可以作为函数的参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
>>> def func():
>>> print('Hello')
>>> print(globals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001EB9E7BB4E0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/Code/python/3.py', '__cached__': None, 'func': <function func at 0x000001EB9CBA1E18>}
# 其中'func': <function func at 0x000001EB9CBA1E18>
>>> print(func)
<function func at 0x000001EB9CBA1E18

>>> def func():
>>> print('Hello')
>>> func1 = func
>>> func1()
Hello

>>> def func1():
>>> print('Hello')
>>> def func2():
>>> print('World')
>>> for i in [func1, func2]:
>>> i()
Hello
World

>>> def func1():
>>> print('Hello')
>>> return func2
>>> def func2():
>>> print('World')
>>> run = func1()
>>> run()
Hello
World

>>> def func1(func):
>>> func()
>>> return func
>>> def func2():
>>> print('World')
>>> run = func1(func2)
>>> run()
World
World

3.内建模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>> # Python v3.6.6
>> import builtins
>> print(len(dir(builtins)), dir(builtins))
152 ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']


>> # Python v2.7.15
>> import __builtin__
>> print(len(dir(__builtin__)), dir(__builtin__))
(143, ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'])

# 交集
127 {'None', 'bool', 'frozenset', 'memoryview', 'Exception', 'print', 'vars', 'min', 'bin', 'license', 'bytes', 'eval', 'ArithmeticError', 'credits', 'map', '__doc__', 'help', '__debug__', 'compile', 'TypeError', 'ImportWarning', 'ZeroDivisionError', 'UnicodeEncodeError', 'range', 'Ellipsis', 'StopIteration', 'format', 'ImportError', 'RuntimeError', 'UnicodeTranslateError', 'UnboundLocalError', 'isinstance', 'hex', 'pow', 'UnicodeDecodeError', 'DeprecationWarning', 'FutureWarning', 'ValueError', 'sorted', 'callable', 'NotImplemented', 'reversed', 'str', 'FloatingPointError', 'oct', 'OverflowError', 'TabError', 'SyntaxWarning', 'len', 'EOFError', 'tuple', '__name__', 'next', 'False', 'dir', 'input', 'KeyError', 'complex', 'exit', 'id', 'AssertionError', 'BaseException', 'SystemExit', 'ord', 'open', 'BytesWarning', 'NameError', 'AttributeError', 'UnicodeWarning', 'hasattr', 'UserWarning', 'quit', 'RuntimeWarning', 'hash', 'Warning', 'setattr', 'SystemError', 'enumerate', 'MemoryError', 'set', 'delattr', 'object', 'BufferError', 'dict', 'max', 'OSError', 'IOError', 'True', 'chr', 'float', '__package__', 'GeneratorExit', 'ReferenceError', 'KeyboardInterrupt', 'filter', 'SyntaxError', 'EnvironmentError', 'abs', 'LookupError', 'UnicodeError', 'int', 'IndexError', 'all', 'iter', 'getattr', 'list', 'classmethod', 'slice', 'staticmethod', 'bytearray', 'copyright', 'locals', 'any', 'PendingDeprecationWarning', 'type', 'NotImplementedError', 'divmod', 'issubclass', 'IndentationError', '__import__', 'super', 'globals', 'repr', 'zip', 'sum', 'round', 'property'}

# Python2
16 ['StandardError', 'apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile', 'file', 'intern', 'long', 'raw_input', 'reduce', 'reload', 'unichr', 'unicode', 'xrange']

# Python3
25 ['BlockingIOError', 'BrokenPipeError', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'FileExistsError', 'FileNotFoundError', 'InterruptedError', 'IsADirectoryError', 'ModuleNotFoundError', 'NotADirectoryError', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ResourceWarning', 'StopAsyncIteration', 'TimeoutError', 'WindowsError', '__build_class__', '__loader__', '__spec__', 'ascii', 'exec']
builtins(Python3)description(详见builtins.py)
ArithmeticError所有数值计算错误的基类
AssertionError断言语句失败
AttributeError对象没有这个属性
BaseException所有异常的基类
BlockingIOErrorI/O operation would block
BrokenPipeErrorBroken pipe
BufferErrorBuffer error
BytesWarningmostly related to conversion from str or comparing to str
ChildProcessErrorChild process error
ConnectionAbortedErrorConnection aborted
ConnectionErrorConnection error
ConnectionRefusedErrorConnection refused
ConnectionResetErrorConnection reset
DeprecationWarning关于被弃用的特征的警告
EOFError没有内建输入,到达EOF标记
EllipsisEllipsis represents ‘…’ in slices
EnvironmentError操作系统错误的基类
Exception常规错误的基类
FalseFalse
FileExistsErrorFile already exists
FileNotFoundErrorFile not found
FloatingPointError浮点计算错误
FutureWarning关于构造将来语义会有改变的警告
GeneratorExit生成器(generator)发生异常来通知退出
IOError输入/输出操作失败
ImportError导入模块/对象失败
ImportWarningprobable mistakes in module imports
IndentationError缩进错误
IndexError序列中没有此索引(index)
InterruptedErrorInterrupted by signal
IsADirectoryErrorOperation doesn’t work on directories
KeyError映射中没有这个键
KeyboardInterrupt用户中断执行(通常是输入^C)
LookupError无效数据查询的基类
MemoryError内存溢出错误(对于Python 解释器不是致命的)
ModuleNotFoundErrorModule not found
NameError未声明/初始化对象 (没有属性)
NoneNone
NotADirectoryErrorOperation only works on directories
NotImplementedMethod or function hasn’t been implemented yet
NotImplementedError尚未实现的方法
OSError操作系统错误
OverflowError数值运算超出最大限制
PendingDeprecationWarning关于特性将会被废弃的警告
PermissionErrorNot enough permissions
ProcessLookupErrorProcess not found
RecursionErrorRecursion limit exceeded
ReferenceError弱引用(Weak reference)试图访问已经垃圾回收了的对象
ResourceWarningresource usage
RuntimeError一般的运行时错误
RuntimeWarning可疑的运行时行为(runtime behavior)的警告
StopAsyncIterationSignal the end from iterator.__anext__()
StopIteration迭代器没有更多的值
SyntaxErrorPython 语法错误
SyntaxWarning可疑的语法的警告
SystemError一般的解释器系统错误
SystemExit解释器请求退出
TabErrorTab 和空格混用
TimeoutErrorTimeout expired
TrueTrue
TypeError对类型无效的操作
UnboundLocalError访问未初始化的本地变量
UnicodeDecodeErrorUnicode 解码时的错误
UnicodeEncodeErrorUnicode 编码时错误
UnicodeErrorUnicode 相关的错误
UnicodeTranslateErrorUnicode 转换时错误
UnicodeWarningUnicode conversion problems
UserWarning用户代码生成的警告
ValueError传入无效的参数
Warning警告的基类
WindowsError系统调用失败
ZeroDivisionError除(或取模)零 (所有数据类型)
__build_class__\
__debug__\
__doc__\
__import__\
__loader__\
__name__\
__package__\
__spec__\
abs详细信息
all详细信息
any详细信息
ascii详细信息
bin详细信息
bool详细信息
bytearray详细信息
bytes详细信息
callable详细信息
chr详细信息
classmethod详细信息
compile详细信息
complex详细信息
copyright详细信息
credits详细信息
delattr详细信息
dict详细信息
dir详细信息
divmod详细信息
enumerate详细信息
eval详细信息
exec详细信息
exit详细信息
filter详细信息
float详细信息
format详细信息
frozenset详细信息
getattr详细信息
globals详细信息
hasattr详细信息
hash详细信息
help详细信息
hex详细信息
id详细信息
input详细信息
int详细信息
isinstance详细信息
issubclass详细信息
iter详细信息
len详细信息
license详细信息
list详细信息
locals详细信息
map详细信息
max详细信息
memoryview详细信息
min详细信息
next详细信息
object详细信息
oct详细信息
open详细信息
ord详细信息
pow详细信息
print详细信息
property详细信息
quit详细信息
range详细信息
repr详细信息
reversed详细信息
round详细信息
set详细信息
setattr详细信息
slice详细信息
sorted详细信息
staticmethod详细信息
str详细信息
sum详细信息
super详细信息
tuple详细信息
type详细信息
vars详细信息
zip详细信息

# abs(x)

1
2
3
4
5
6
7
8
9
""" Return the absolute value of the argument. """


>>> print(abs(-1))
1
>>> print(abs(-1.3))
1.3
>>> print(abs(-1+3j))
3.1622776601683795

# all(iterable)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"""
Return True if bool(x) is True for all values x in the iterable.

If the iterable is empty, return True.
"""
# 全为真时结果为真
# 为空时为真

>>> list_a = [1, '2', (3,), [4, 5], {'user': 'pwd'}, {6, 7}]
>>> list_b = [1, '', (3,), [4, 5], {'user': 'pwd'}, {4, 5}]
>>> list_c = ''
>>> list_d = []
>>> list_e = ()
>>> list_f = {}
>>> list_g = set()
>>> print(all(list_a))
True
>>> print(all(list_b))
False
>>> print(all(list_c), all(list_d), all(list_e), all(list_f), all(list_g))
True True True True True

# any(iterable)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"""
Return True if bool(x) is True for any x in the iterable.

If the iterable is empty, return False.
"""
# 有一个为真结果就为真


>>> list_a = [1, '', (), [], {}, set()]
>>> list_b = [0, '', (), [], {}, set()]
>>> list_c = ''
>>> list_d = []
>>> list_e = ()
>>> list_f = {}
>>> list_g = set()
>>> print(any(list_a))
True
>>> print(any(list_b))
False
>>> print(any(list_c), any(list_d), any(list_e), any(list_f), any(list_g))
False False False False False

# ascii(object)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""
Return an ASCII-only representation of an object.

As repr(), return a string containing a printable representation of an
object, but escape the non-ASCII characters in the string returned by
repr() using \\x, \\u or \\U escapes. This generates a string similar
to that returned by repr() in Python 2.
"""
# ascii() 函数类似 repr() 函数, 返回一个表示对象的字符串, 但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符。 生成字符串类似 Python2 版本中 repr() 函数的返回值。


>>> print(ascii(1))
1
>>> print(ascii('a'))
'a'
>>> print(ascii('●'))
'\u25cf'

# bin(x)

1
2
3
4
5
6
"""
Return the binary representation of an integer.

>>> bin(2796202)
'0b1010101010101010101010'
"""

# bool(int)

1
2
3
4
5
6
7
8
9
10
11
"""
bool(x) -> bool

Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.
"""


>>> print(issubclass(bool, int))
True

# bytearray([source[, encoding[, errors]]])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
bytearray() -> empty bytes array

Construct a mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a buffer object
- any object implementing the buffer API.
- an integer
"""
# 可变mutable
如果 source 为整数,则返回一个长度为 source 的初始化数组;
如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列;
如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数;
如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。
如果没有输入任何参数,默认就是初始化数组为0个元素。

>>> print(bytearray([1, 2, 3]))
bytearray(b'\x01\x02\x03')
>>> print(bytearray('Conyyon', encoding='utf-8'))
bytearray(b'Conyyon')
>>> print(bytearray(1))
bytearray(b'\x00')
>>> print(bytearray())
bytearray(b'')

# bytes([source[, encoding[, errors]]])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object

Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer
"""
# 不可变immutable

>>> print(bytes([1, 2, 3]))
b'\x01\x02\x03'
>>> print(bytes('Conyyon', encoding='utf-8'))
b'Conyyon'
>>> print(bytes(1))
b'\x00'
>>> print(bytes())
b''

# callable(object)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""
Return whether the object is callable (i.e., some kind of function).

Note that classes are callable, as are instances of classes with a
__call__() method.
"""


>>> print(callable(1))
False
>>> def func(): pass
>>> print(callable(func))
True
>>> class Fun:
>>> def __init__(self): pass
>>> print(callable(Fun))
True
>>> fun = Fun()
>>> print(callable(fun))
False
>>> class Fun:
>>> def __init__(self): pass
>>> def __call__(self, *args, **kwargs): pass
>>> print(callable(Fun))
True
>>> fun = Fun()
>>> print(callable(fun))
True

# chr(code)

1
2
3
4
5
6
7
""" Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """
# 返回整数对应的ASCII字符

>>> print(chr(65), chr(0x41))
A A
>>> print(chr(97), chr(0x61))
a a

# classmethod()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument,
just like an instance method receives the instance.
To declare a class method, use this idiom:

class C:
@classmethod
def f(cls, arg1, arg2, ...):
...

It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()). The instance is ignored except for its class.
If a class method is called for a derived class, the derived class
object is passed as the implied first argument.

Class methods are different than C++ or Java static methods.
If you want those, see the staticmethod builtin.
"""
# 后文面向对象

# compile(source, filename, mode[, flags[, dont_inherit]])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
Compile source into a code object that can be executed by exec() or eval().

The source code may represent a Python module, statement or expression.
The filename will be used for run-time error messages.
The mode must be 'exec' to compile a module, 'single' to compile a
single (interactive) statement, or 'eval' to compile an expression.
The flags argument, if present, controls which future statements influence
the compilation of the code.
The dont_inherit argument, if true, stops the compilation inheriting
the effects of any future statements in effect in the code calling
compile; if absent or false these statements do influence the compilation,
in addition to any features explicitly specified.
"""
# 能够通过exec()和eval()方法将一个字符串编译为字节代码。

# complex([real[, imag]])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
Create a complex number from a real part and an optional imaginary part.

This is equivalent to (real + imag*1j) where imag defaults to 0.
"""


>>> print(complex(0.2, 2))
(0.2+2j)
>>> print(complex(1, 0.5))
(1+0.5j)
>>> print(complex('1.6'))
(1.6+0j)
>>> print(complex('1+4j'))
(1+4j)

# copyright()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""
interactive prompt objects for printing the license text, a list of contributors and the copyright notice.
"""


>>> copyright()
Copyright (c) 2001-2018 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.

# credits()

1
2
3
4
5
6
7
8
"""
interactive prompt objects for printing the license text, a list of contributors and the copyright notice.
"""


>>> credits()
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information.

# delattr(object, name)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
Deletes the named attribute from the given object.

delattr(x, 'y') is equivalent to ``del x.y''
"""


>>> class Test:
>>> attribute_x = 'Hello'
>>> attribute_y = 'Python'
>>> test = Test()
>>> print('attribute_x' in test.__dir__(), test.attribute_x)
True Hello
>>> print('attribute_y' in test.__dir__(), test.attribute_y)
True Python
>>> delattr(Test, 'attribute_x')
>>> print('attribute_x' in test.__dir__())
False
>>> print('attribute_y' in test.__dir__(), test.attribute_y)
True Python
>>> del Test.attribute_y
>>> print('attribute_y' in test.__dir__())
False

# dict()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
"""


>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

# dir([object])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"""
dir([object]) -> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes of its bases.
for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.
"""


>>> print(dir())
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
>>> print(dir(''))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> print(dir([]))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

# divmod(a, b)

1
2
3
4
5
6
7
8
9
10
11
12
13
""" Return the tuple (x//y, x%y).  Invariant: div*y + mod == x. """


>>> print(divmod(3, 2))
(1, 1)
>>> print(divmod(3.2, 2))
(1.0, 1.2000000000000002)
>>> print(divmod(3, 2.5))
(1.0, 0.5)
>>> print(divmod(3.8, 0.2))
(18.0, 0.19999999999999962)
>>> print(divmod(7+2j, 4+5j))
TypeError: can't take floor or mod of complex number.

# enumerate(sequence, [start=0])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""
Return an enumerate object.

iterable
an object supporting iteration

The enumerate object yields pairs containing a count (from start, which
defaults to zero) and a value yielded by the iterable argument.

enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
"""


>>> list_t = ['A', 'B', 'C']
>>> print(list(enumerate(list_t)))
[(0, 'A'), (1, 'B'), (2, 'C')]
>>> print(list(enumerate(list_t, 1)))
[(1, 'A'), (2, 'B'), (3, 'C')]
>>> for index, i in enumerate(list_t, 2):
>>> print(index, i)
2 A
3 B
4 C

# eval(expression[, globals[, locals]])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
Evaluate the given source in the context of globals and locals.

The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
"""
# 有返回值


>>> a = 3
>>> print(eval('a'))
3
>>> print(eval('a + 5'))
8
>>> print(eval('pow(a, 3)'))
27

# exec(object[, globals[, locals]])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"""
Execute the given source in the context of globals and locals.

The source may be a string representing one or more Python statements
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
"""
# 无返回值(None)


>>> a = 3
>>> exec('print(a)')
3
>>> exec('print(a+b)', {'a': '4', 'b': '5'})
45

# exit()

1
pass

# filter(function, iterable)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"""
filter(function or None, iterable) --> filter object

Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
"""
# 过滤
# 将可迭代对象中的每个元素作为参数传给函数,并将函数返回值为True的元素放到迭代器中,最后返回迭代器。

>>> def even(x): return x % 2 == 0
>>> print(list(filter(even, range(11))))
[0, 2, 4, 6, 8, 10]
>>> print(list(filter(lambda x: x % 2 == 0, range(11))))
[0, 2, 4, 6, 8, 10]

# float([x])

1
2
3
4
5
6
7
8
9
10
11
""" Convert a string or number to a floating point number, if possible. """


>>> print(float(5))
5.0
>>> print(float(6.8))
6.8
>>> print(float('6'))
6.0
>>> print(float('6.5'))
6.5

# format()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
Return value.__format__(format_spec)

format_spec defaults to the empty string.
See the Format Specification Mini-Language section of help('FORMATTING') for
details.
"""


>>> print('My name is {}, I am {} years old'.format('Tom', 21))
My name is Tom, I am 21 years old
>>> print('My name is {0}, I am {1} years old'.format('Tom', 21))
My name is Tom, I am 21 years old
>>> print('My name is {name}, I am {age} years old'.format(name='Tom', age=21))
My name is Tom, I am 21 years old
>>> print('My name is {name}, I am {name} years old'.format(name='Tom', age=21))
My name is Tom, I am Tom years old
>>> print('{} {{}}'.format('Hello'))
Hello {}

输入格式化输入描述
1.123456{:.2f}1.12保留小数点后两位
1.123456{:+.2f}+1.12带符号保留小数点后两位
-1.123456{:-.2f}-1.12带符号保留小数点后两位
1.123456{:.0f}1四舍五入不带小数
1.523456{:.0f}2四舍五入不带小数
1523456{:10d}   1523456宽度为10,默认右对齐
1523456{:>10d}   1523456宽度为10,右对齐,默认空格填充
1523456{:*10d}***1523456宽度为10,右对齐,*填充
1523456{:^10d} 1523456  宽度为10,居中对齐,默认空格填充
1523456{:#^10d}#1523456##宽度为10,居中对齐,#填充
1523456{:<10d}1523456   宽度为10,左对齐,默认空格填充
1523456{:&<10d}1523456&&&宽度为10,左对齐,&填充
1523456{:,}1,523,456逗号分隔的数字
1523456{:.0%}152345600%百分制,保留小数点0位
1523456{:.2%}152345600.00%百分制,保留小数点2位
1523456{:.0e}2e+06科学计数法,保留小数点0位
1523456{:.2e}1.52e+06科学计数法,保留小数点2位
10{:b}1010二进制转换
10{:#b}0b1010(“带头”)二进制转换
10{:o}12八进制转换
10{:#o}0o12(“带头”)八进制转换
10{:d}10十进制转换
10{:x}a十六进制转换
10{:#x}0xa(“带头”)十六进制转换
10{:X}A十六进制转换(大写)
10{:#X}0xA(“带头”)十六进制转换(大写)

# frozenset([iterable])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
frozenset() -> empty frozenset object
frozenset(iterable) -> frozenset object

Build an immutable unordered collection of unique elements.
"""
# 冻结的集合,不可变集合


>>> print(frozenset(range(5)))
frozenset({0, 1, 2, 3, 4})
>>> print(frozenset(['A', 'B', 'C']))
frozenset({'A', 'C', 'B'})
>>> print(frozenset().__dir__())
['__repr__', '__hash__', '__getattribute__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__iter__', '__sub__', '__rsub__', '__and__', '__rand__', '__xor__', '__rxor__', '__or__', '__ror__', '__len__', '__contains__', '__new__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', '__reduce__', '__sizeof__', 'symmetric_difference', 'union', '__doc__', '__str__', '__setattr__', '__delattr__', '__init__', '__reduce_ex__', '__subclasshook__', '__init_subclass__', '__format__', '__dir__', '__class__']

# getattr(object, name[, default])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"""
getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
# 见后文反射

>>> class Test:
>>> name = 'Python'
>>> @staticmethod
>>> def func():
>>> return 'Hello'
>>> t1 = Test()
>>> print(getattr(t1, 'name'))
Python
>>> print(getattr(t1, 'func'))
<function Test.func at 0x00000164AC0F5048>
>>> print(getattr(t1, 'age', 21))
21

# globals()

1
2
3
4
5
6
7
8
9
10
11
"""
Return the dictionary containing the current scope's global variables.

NOTE: Updates to this dictionary *will* affect name lookups in the current
global scope and vice-versa.
"""


>>> str_a = 'Python'
>>> print(globals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000019A056FB240>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/Code/python/test/test4.py', '__cached__': None, 'str_a': 'Python'}

# hasattr(object, name)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
Return whether the object has an attribute with the given name.

This is done by calling getattr(obj, name) and catching AttributeError.
"""
# 见后文反射

>>> class Test:
>>> name = 'Python'
>>> @staticmethod
>>> def func():
>>> return 'Hello'
>>> t1 = Test()
>>> print(hasattr(t1, 'name'))
True
>>> print(hasattr(t1, 'func'))
True
>>> print(hasattr(t1, 'age'))
False

# hash(object)

1
2
3
4
5
6
7
8
9
10
11
12
"""
Return the hash value for the given object.

Two objects that compare equal must also have the same hash value, but the
reverse is not necessarily true.
"""


>>> str_a = 'Python'
>>> str_b = 'Python'
>>> print(hash(str_a), hash(str_a), hash(str_a) == hash(str_a))
1601920978270115665 1601920978270115665 True

# help([object])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
Define the builtin 'help'.

This is a wrapper around pydoc.help that provides a helpful message
when 'help' is typed at the Python interactive prompt.

Calling help() at the Python prompt starts an interactive help session.
Calling help(thing) prints help for the python object 'thing'.
"""


>>> help(str.title)
Help on method_descriptor:

title(...)
S.title() -> str

Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.

# hex(x)

1
2
3
4
5
6
"""
Return the hexadecimal representation of an integer.

>>> hex(12648430)
'0xc0ffee'
"""

# id([object])

1
2
3
4
5
6
7
8
9
10
"""
Return the identity of an object.

This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object's memory address.)
"""


>>> print(id(1))
1693215776

# input([prompt])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
Read a string from standard input. The trailing newline is stripped.

The prompt string, if given, is printed to standard output without a
trailing newline before reading input.

If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
"""


>>> name = input('Please input your name:')
>>> print(type(name), name)
Please input your name:Conyyon
<class 'str'> Conyyon

# int(x, base=10)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""
int([x]) -> integer
int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
"""


>>> print(int(1.6))
1
>>> print(int('11', base=2))
3
>>> print(int('14', base=8))
12
>>> print(int('18', base=10))
18
>>> print(int('2A', base=16))
42

# isinstance(object, classinfo)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""
Return whether an object is an instance of a class or of a subclass thereof.

A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
or ...`` etc.
"""
# isinstance() 与 type() 区别:
# type() 不会认为子类是一种父类类型,不考虑继承关系。
# isinstance() 会认为子类是一种父类类型,考虑继承关系。
# 如果要判断两个类型是否相同推荐使用 isinstance()。


>>> print(isinstance(1, int))
True
>>> print(isinstance(1, str))
False
>>> print(isinstance([1], (int, str, list)))
True
>>> print(isinstance((1,), (int, str, list)))
False
>>> class A: pass
>>> class B(A): pass
>>> print(isinstance(A(), A))
True
>>> print(type(A()) == A)
True
>>> print(isinstance(B(), A))
True
>>> print(type(B()) == A)
False

# issubclass(object, classinfo)

1
2
3
4
5
6
7
8
9
10
11
12
13
"""
Return whether 'cls' is a derived from another class or is the same class.

A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
or ...`` etc.
"""


>>> class A: pass
>>> class B(A): pass
>>> print(issubclass(B, A))
True

# iter(object[, sentinel])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"""
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator

Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
"""


>>> list_a = ['A', 'B', 'C']
>>> print(iter(list_a))
<list_iterator object at 0x0000025128BB8908>
>>> print(i for i in list_a)
<generator object <genexpr> at 0x0000025128B21E08>
>>> print([i for i in list_a])
['A', 'B', 'C']
>>> for i in list_a:
>>> print(i, end='')
ABC

# len(s)

1
2
3
4
5
""" Return the number of items in a container. """


>>> print(len('ABCDEFG'))
7

# license()

1
2
3
4
5
6
7
8
9
10
11
"""
interactive prompt objects for printing the license text, a list of
contributors and the copyright notice.
"""


>>> license()
A. HISTORY OF THE SOFTWARE
==========================

Python was created in the early 1990s by Guido van Rossum at Stichting......

# list(seq)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"""
Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.
"""


>>> str_a = 'ABC'
>>> tuple_a = ('A', 'B', 'C')
>>> print(list(str_a))
['A', 'B', 'C']
>>> print(list(tuple_a))
['A', 'B', 'C']

# locals()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"""
Return a dictionary containing the current scope's local variables.

NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
"""


>>> print(locals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000214C385B240>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/Code/python/test/test4.py', '__cached__': None}
>>> def func(a):
>>> b = 2
>>> print(locals())
>>> func(1)
{'b': 2, 'a': 1}

# map(function, iterable, …)

1
2
3
4
5
6
7
8
9
10
11
12
"""
map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
"""
# 将可迭代对象中的每个元素作为参数传给函数,函数操作后将返回的结果放到迭代器中,最后返回迭代器。

>>> print(list(map(lambda x: pow(x, 2), [1, 2, 3, 4, 5])))
[1, 4, 9, 16, 25]
>>> print(list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])))
[3, 7, 11, 15, 19]

# max(x, y, z, …)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"""
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value

With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
"""


>>> print(max(1, 2))
2
>>> print(max([1, 2]))
2
>>> print(max([1, 2, -3]))
2
>>> print(max([1, 2, -3], key=abs))
-3
>>> print(max([1, 2, -3], key=lambda x: abs(x)))
-3

# memoryview(object)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
""" Create a new memoryview object which references the given object. """


>>> view = memoryview(b'abcefg')
>>> print(view[0])
97
>>> view = memoryview(bytearray("abcefg", encoding='utf-8'))
>>> print(view[1])
98
>>> view = memoryview(bytes('abcefg', encoding='utf-8'))
>>> print(view[2])
99
>>> print(view[0:5].tobytes())
b'abcef'
>>> print(view[0:5].tolist())
[97, 98, 99, 101, 102]

# min(x, y, z, …)

1
2
3
4
5
6
7
8
9
"""
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value

With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
"""

# next(iterator[, default])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"""
next(iterator[, default])

Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
"""


>>> _iter = iter(range(5))
>>> while 1:
>>> try:
>>> nxt = next(_iter)
>>> print(nxt, end=' ')
>>> except StopIteration:
>>> break
0 1 2 3 4

# object()

1
""" The most base type """

# oct(x)

1
2
3
4
5
6
"""
Return the octal representation of an integer.

>>> oct(342391)
'0o1234567'
"""

# open(file, mode=’r’, buffering=None, encoding=None, errors=None, newline=None, closefd=True)

1
pass

# ord(c)

1
2
3
4
5
6
7
""" Return the Unicode code point for a one-character string. """


>>> print(ord('A'))
65
>>> print(ord('a'))
97

# pow(x, y[, z])

1
2
3
4
5
6
7
8
9
10
11
12
"""
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
"""


>>> print(pow(2, 3))
8
>>> print(pow(2, 3, 5))
3

# print(*objects, sep=’ ‘, end=’\n’, file=None)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
"""

>>> import time
>>> print(1, 2, 3, 4, 5)
1 2 3 4 5
>>> print(1, 2, 3, 4, 5, sep='-')
1-2-3-4-5
>>> for i in range(1, 6):
>>> print(i, end='*', flush=True)
1*2*3*4*5*

# property()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
Property attribute.

fget
function to be used for getting an attribute value
fset
function to be used for setting an attribute value
fdel
function to be used for del'ing an attribute
doc
docstring

Typical use is to define a managed attribute x:

class C(object):
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")

Decorators make defining new properties or modifying existing ones easy:

class C(object):
@property
def x(self):
"I am the 'x' property."
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
"""
# 后文面向对象

# quit()

1
pass

# range(start, stop[, step])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
range(stop) -> range object
range(start, stop[, step]) -> range object

Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements.
When step is given, it specifies the increment (or decrement).
"""


>>> print(range(5))
range(0, 5)
>>> print(list(range(5)))
[0, 1, 2, 3, 4]
>>> for i in range(0, 5, 2):
>>> print(i, end=' ')
0 2 4
>>> print()
>>> for i in range(5, -1, -1):
>>> print(i, end=' ')
5 4 3 2 1 0

# repr(object)

1
2
3
4
5
"""
Return the canonical string representation of the object.

For many object types, including most builtins, eval(repr(obj)) == obj.
"""

# reversed(seq)

1
2
3
4
5
6
7
8
9
10
11
12
""" Return a reverse iterator over the values of the given sequence. """


# 返回一个翻转序列的迭代器
>>> print(list(reversed(range(5))))
[4, 3, 2, 1, 0]
>>> print(list(reversed('ABC')))
['C', 'B', 'A']
>>> print(list(reversed(['A', 'B', 'C'])))
['C', 'B', 'A']
>>> print(list(reversed(('A', 'B', 'C'))))
['C', 'B', 'A']

# round(x [, n])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
Round a number to a given precision in decimal digits.

The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
"""
# 四舍五入受精度影响


>>> print(round(1.6))
2
>>> print(round(1.535, 2))
1.53
>>> print(round(10.54545, 4))
10.5455

# set(x [, n])

1
2
3
4
5
6
7
8
9
10
"""
set() -> new empty set object
set(iterable) -> new set object

Build an unordered collection of unique elements.
"""


>>> print(set('Python'))
{'P', 'o', 'y', 't', 'n', 'h'}

# setattr(object, name, value)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
"""
Sets the named attribute on the given object to the specified value.

setattr(x, 'y', v) is equivalent to ``x.y = v''
"""
# 见后文反射

>>> class Test:
>>> name = 'Python'
>>> test = Test()
>>> print(test.name)
Python
>>> setattr(test, 'name', 'Conyyon')
>>> print(test.name)
Conyyon
>>> setattr(test, 'age', 20)
>>> print(test.age)
20

# slice(start, stop[, step])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
slice(stop)
slice(start, stop[, step])

Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
"""


>>> list_a = list(range(10))
>>> print(list_a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(list_a[:5])
[0, 1, 2, 3, 4]
>>> print(list_a[slice(5)])
[0, 1, 2, 3, 4]
>>> print(list_a[1:5])
[1, 2, 3, 4]
>>> print(list_a[slice(1, 5)])
[1, 2, 3, 4]
>>> print(list_a[1:5:2])
[1, 3]
>>> print(list_a[slice(1, 5, 2)])
[1, 3]

# sorted(iterable, key=None, reverse=False)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
"""
# sort 与 sorted 区别:
# sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
# list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的list,而不是在原来的基础上进行的操作。


>>> list_a = [3, 6, 5, 1, 2, 8, 4, 9, 7]
>>> list_b = sorted(list_a)
>>> list_c = sorted(list_a, reverse=True)
>>> list_d = sorted(list_a, key=lambda x: pow(x, -1))
>>> print(list_a)
[3, 6, 5, 1, 2, 8, 4, 9, 7]
>>> print(list_b)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(list_c)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> print(list_d)
[9, 8, 7, 6, 5, 4, 3, 2, 1]

# staticmethod()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"""
staticmethod(function) -> method

Convert a function to be a static method.

A static method does not receive an implicit first argument.
To declare a static method, use this idiom:

class C:
@staticmethod
def f(arg1, arg2, ...):
...

It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++.
For a more advanced concept, see the classmethod builtin.
"""
# 后文面向对象

# str(object=’’)

1
2
3
4
5
6
7
8
9
10
11
12
"""
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
"""

# sum(iterable[, start])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
Return the sum of a 'start' value (default: 0) plus an iterable of numbers

When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
"""


>>> print(sum([1, 2, 3]))
6
>>> print(sum((1, 2, 3), 1))
7
>>> print(sum([1, 2, 3], 2))
8

# super(type[, object-or-type])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"""
super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
class C(B):
def meth(self, arg):
super().meth(arg)
This works for class methods too:
class C(B):
@classmethod
def cmeth(cls, arg):
super().cmeth(arg)
"""
# 面向对象

# tuple(seq)

1
2
3
4
5
6
7
8
"""
Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple.
If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.
"""

# type()

1
2
3
4
5
6
"""
type(object_or_name, bases, dict)
type(object) -> the object's type
type(name, bases, dict) -> a new type
"""
# 后文元类

# vars([object])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"""
vars([object]) -> dictionary

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
"""

>>> print(vars())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001DA9432B240>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/Code/python/test/test4.py', '__cached__': None}
>>> print(vars(tuple))
{'__repr__': <slot wrapper '__repr__' of 'tuple' objects>, '__hash__': <slot wrapper '__hash__' of 'tuple' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'tuple' objects>, '__lt__': <slot wrapper '__lt__' of 'tuple' objects>, '__le__': <slot wrapper '__le__' of 'tuple' objects>, '__eq__': <slot wrapper '__eq__' of 'tuple' objects>, '__ne__': <slot wrapper '__ne__' of 'tuple' objects>, '__gt__': <slot wrapper '__gt__' of 'tuple' objects>, '__ge__': <slot wrapper '__ge__' of 'tuple' objects>, '__iter__': <slot wrapper '__iter__' of 'tuple' objects>, '__len__': <slot wrapper '__len__' of 'tuple' objects>, '__getitem__': <slot wrapper '__getitem__' of 'tuple' objects>, '__add__': <slot wrapper '__add__' of 'tuple' objects>, '__mul__': <slot wrapper '__mul__' of 'tuple' objects>, '__rmul__': <slot wrapper '__rmul__' of 'tuple' objects>, '__contains__': <slot wrapper '__contains__' of 'tuple' objects>, '__new__': <built-in method __new__ of type object at 0x0000000064E5C0D0>, '__getnewargs__': <method '__getnewargs__' of 'tuple' objects>, 'index': <method 'index' of 'tuple' objects>, 'count': <method 'count' of 'tuple' objects>, '__doc__': "tuple() -> empty tuple\ntuple(iterable) -> tuple initialized from iterable's items\n\nIf the argument is a tuple, the return value is the same object."}
>>> def func(a):
>>> b = 2
>>> print(vars())
>>> func(1)
{'b': 2, 'a': 1}

# zip([iterable, …])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
zip(iter1 [,iter2 [...]]) --> zip object

Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument. The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration.
"""


>>> print(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))
<zip object at 0x000001D9C2994608>
>>> print(list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9])))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> print(list(zip([1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11, 12])))
[(1, 4, 8), (2, 5, 9), (3, 6, 10)]
>>> a, b, c = zip(*zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))
>>> print(a, b, c)
(1, 2, 3) (4, 5, 6) (7, 8, 9)

# reduce(function, sequence, initial=None)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"""
reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
"""


>>> from functools import reduce
>>> print(reduce(lambda x, y: x*y, [1, 2, 3]))
6
>>> print(reduce(lambda x, y: x*y, [], 4))
4
>>> print(reduce(lambda x, y: x*y, [1, 2, 3], 4))
24

4.装饰器

不修改函数的调用方式,在原来的函数前后添加功能。开放(扩展是开放的)封闭(修改是封闭的)原则。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 闭包:嵌套函数,内部函数对外部函数(非全局)变量的引用
# __closure__ 来检测函数是否是闭包,使用函数名.__closure__返回cell就是闭包,返回None就不是闭包
# 如果一个函数执行完毕,则这个函数中的变量以及局部命名空间中的内容都将会被销毁。在闭包中,如果变量被销毁了,那内部函数将不能正常执行。所以,python规定,如果在内部函数中访问外层函数中的变量,那么这个变量将不会消亡,将会常驻在内存中。也就是说,使用闭包,可以保证外层函数中的变量在内存中常驻。闭包的作用就是让一个变量能够常驻内存,供后面的程序使用。

>>> def outer():
>>> a = 1
>>> def inner():
>>> print(a)
>>> print(inner.__closure__)
>>> inner()
>>> outer()
(<cell at 0x00000280226586A8: int object at 0x0000000055DF6C20>,)
1
>>> print(outer.__closure__)
None


>>> def outer():
>>> a = 1
>>> def inner():
>>> return a
>>> inner()
>>> ret = outer()
>>> print(ret)
None

>>> def outer():
>>> a = 1
>>> def inner():
>>> return a
>>> return inner()
>>> ret = outer()
>>> print(ret)
1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 装饰器装饰不带参数的函数

>>> import time
>>> def timmer(func): # 装饰器函数
>>> def inner():
>>> print('开始运行...')
>>> start = time.time()
>>> ret = func() # 被装饰的函数
>>> end = time.time()
>>> print('运行结束...')
>>> print('运行时间:', end - start)
>>> return ret
>>> return inner
>>> @timmer # @修饰符加装饰器函数名称(语法糖)
>>> def test(): # 被装饰的函数
>>> time.sleep(1)
>>> print('大家好')
>>> # test = timmer(test) # @timmer等价于此句
>>> test() # 实质执行装饰器中的inner()
开始运行...
大家好
运行结束...
运行时间: 1.000701665878296

# 若@timer和test = timmer(test)两句同时存在,则会重复输出,输出结果如下,可见@timer实质为test = timmer(test)。)(此处结果实质为多个装饰器装饰一个函数,详见后文。)

开始运行...
开始运行...
大家好
运行结束...
运行时间: 1.0003609657287598
运行结束...
运行时间: 1.0003609657287598
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 装饰器装饰带参数的函数

>>> import time
>>> def timmer(func): # 装饰器函数
>>> def inner(*args, **kwargs):
>>> print('开始运行...')
>>> start = time.time()
>>> ret = func(*args, **kwargs) # 被装饰的函数
>>> end = time.time()
>>> print('运行结束...')
>>> print('运行时间:', end - start)
>>> return ret
>>> return inner
>>> @timmer
>>> def test(a, b): # 被装饰的函数
>>> time.sleep(1)
>>> print('大家好', a, b)
>>> test(1, 2)
开始运行...
大家好 1 2
运行结束...
运行时间: 1.0005004405975342
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 带参数的装饰器

>>> import time
>>> flag = True
>>> def timmer_switch(flag):
>>> def timmer(func):
>>> def inner(*args, **kwargs):
>>> if flag:
>>> print('开始运行...')
>>> start = time.time()
>>> ret = func(*args, **kwargs)
>>> end = time.time()
>>> print('运行结束...')
>>> print('运行时间:', end - start)
>>> return ret
>>> else:
>>> # do something
>>> ret = func(*args, **kwargs)
>>> return ret
>>> return inner
>>> return timmer
>>> @timmer_switch(flag)
>>> def test():
>>> time.sleep(1)
>>> print('大家好')
>>> test()
开始运行...
大家好
运行结束...
运行时间: 1.0002727508544922

# 如果flag = False,则输出下列结果

大家好
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 多个装饰器装饰一个函数
从下往上,每装饰一次就把上次的结果作为下次被装饰的内容

>>> def wrapper1(func):
>>> def inner1():
>>> print('wrapper1 before func')
>>> ret = func()
>>> print('wrapper1 after func')
>>> return ret
>>> return inner1
>>> def wrapper2(func):
>>> def inner2():
>>> print('wrapper2 before func')
>>> ret = func()
>>> print('wrapper2 after func')
>>> return ret
>>> return inner2
>>> def wrapper3(func):
>>> def inner3():
>>> print('wrapper3 before func')
>>> ret = func()
>>> print('wrapper3 after func')
>>> return ret
>>> return inner3
>>> @wrapper3
>>> @wrapper2
>>> @wrapper1
>>> def test():
>>> print('test')
>>> test()
wrapper3 before func
wrapper2 before func
wrapper1 before func
test
wrapper1 after func
wrapper2 after func
wrapper3 after func
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 由于调用被装饰函数实际调用装饰器中的内层函数,所以被装饰函数会丢失信息如__name__、__doc__、__module__,为了防止此类现象的发生,调用functools模块中的wraps装饰器,可将原函数对象的指定属性复制给包装函数对象。
# 对带装饰功能的函数添加了@wraps装饰器,可以通过func.__wrapped__方式获得被装饰之前的函数或类来取消装饰器的作用。

>>> def wrapper(func):
>>> def inner(*args, **kwargs):
>>> """inner()说明"""
>>> print('Decorator')
>>> ret = func(*args,**kwargs)
>>> return ret
>>> return inner
>>> @wrapper
>>> def test():
>>> """test()说明"""
>>> print('This is a test.')
>>> print(test.__name__)
>>> print(test.__doc__)
inner
inner()说明


# 导入functools

>>> from functools import wraps
>>> def wrapper(func):
>>> @wraps(func)
>>> def inner(*args, **kwargs):
>>> """inner()说明"""
>>> print('Decorator')
>>> ret = func(*args,**kwargs)
>>> return ret
>>> return inner
>>> @wrapper
>>> def test():
>>> """test()说明"""
>>> print('This is a test.')
>>> print(test.__name__)
>>> print(test.__doc__)
test
test()说明
>>> test()
Decorator
This is a test.
>>> test.__wrapped__()
This is a test.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 完整通用装饰器模板

# 不带参数的装饰器

>>> from functools import wraps
>>> def wrapper(func):
>>> @wraps(func)
>>> def inner(*args, **kwargs):
>>> # 在函数被调用之前的操作
>>> ret = func(*args, **kwargs)
>>> # 在函数被调用之后的操作
>>> return ret
>>> return inner
>>> @wrapper
>>> def test():
>>> # do something
>>> pass


# 带参数的装饰器
>>> from functools import wraps
>>> def decorator(arg)
>>> def wrapper(func):
>>> @wraps(func)
>>> def inner(*args, **kwargs):
>>> # 在函数被调用之前的操作
>>> ret = func(*args, **kwargs)
>>> # 在函数被调用之后的操作
>>> return ret
>>> return inner
>>> return decorator

5.迭代器

可迭代(iterable):含有__iter__()方法是可迭代的(可迭代协议)
迭代器(iterator):含有__next__()和__iter__()方法的是迭代器(迭代器协议)
迭代器一定可迭代,可迭代的可被for循环,可被for循环的可迭代
iterable.__iter()__() = >迭代器
iterator.__next__() 从迭代器中一个一个取值
迭代器的好处:不会一次性在内存中生成全部数据占用很大内存,而是每次利用__next__()获取一个值时,会生成一个,直到获取完所有的值,节省内存空间;惰性机制;不能反复,只能向下执行
for循环迭代器只会循环一次,需要一个值,生成一个值,直至取完迭代器中所有元素位置
for循环非迭代器(如列表等可迭代的数据类型)每次从头开始

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
>>> print('__iter__' in dir(bool))
False
>>> print('__iter__' in dir(int))
False
>>> print('__iter__' in dir(str))
True
>>> print('__iter__' in dir(list))
True
>>> print('__iter__' in dir(dict))
True
>>> print('__iter__' in dir(set))
True
>>> print('__iter__' in dir(tuple))
True
>>> print('__iter__' in dir(enumerate([])))
True
>>> print('__iter__' in dir(range(1)))
True


>>> print([].__iter__())
<list_iterator object at 0x0000022666208B70>
>>> print(set(dir([].__iter__())) - set(dir([])))
{'__setstate__', '__next__', '__length_hint__'}
# __setstate__() 迭代器从第几个开始迭代
# __next__() 从迭代器中取下一个值
# __length_hint__() 迭代器中元素的个数


# for循环内部机制:迭代器取值,取完后break,不会StopIteration

>>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> iterator = list1.__iter__()
>>> print(iterator.__length_hint__())
10
>>> print(iterator.__next__())
1
>>> print(iterator.__next__())
2
>>> print(iterator.__next__())
3
>>> print(iterator.__next__())
4
>>> iterator.__setstate__(8)
>>> print(iterator.__next__())
9
>>> print(iterator.__next__())
10
>>> print(iterator.__next__())
StopIteration


>>> list1 = [1, 2, 3, 4, 5]
>>> iterator = iter(list1)
>>> print(next(iterator, None))
1
>>> print(next(iterator, None))
2
>>> print(next(iterator, None))
3
>>> print(next(iterator, None))
4
>>> print(next(iterator, None))
5
>>> print(next(iterator, None))
None


# 使用while循环和迭代器模拟for循环
>>> lst = [1, 2, 3]
>>> lst_2 = iter(lst)
>>> while True:
>>> try:
>>> i = next(lst_2)
>>> print(i)
>>> except StopIteration:
>>> break
1
2
3
1
2
3
4
5
6
7
8
9
10
11
12
13
# 通过collections模块的Iterable判断对象是否可迭代

>>> from collections import Iterable,Iterator
>>> lst = [1, 2, 3]
>>> print(isinstance(lst, Iterable))
True
>>> print(isinstance(lst, Iterator))
False
>>> lst_2 = iter(lst)
>>> print(isinstance(lst_2, Iterable))
True
>>> print(isinstance(lst_2, Iterator))
True

6.生成器

generator生成器和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而generator生成器函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行
生成器本质是迭代器
含有yield关键字的函数都是生成器函数。首先利用def定义一个生成器函数,接着调用生成器函数,函数不会执行,而是会创建一个生成器,最后利用创建的生成器进行取值操作。
yield不能和return共用且yield需要写在函数内
生成器的惰性机制: 生成器只有在访问的时候才取值,你找它要才给你值,不找它要,它是不会执行的
生成器取值:next()、for、数据类型强转(占用内存)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 生成器函数

>>> def generator():
>>> for i in range(1, 5):
>>> yield '*'*i
>>> g = generator()
>>> print(g)
<generator object generator at 0x0000028ADECDE048>
>>> print(next(g))
*
>>> print(next(g))
**
>>> print(next(g))
***
>>> print(next(g))
****
>>> print(next(g))
StopIteration


>>> def generator():
>>> print('Python')
>>> data1 = yield 5
>>> print('Hello', data1)
>>> data2 = yield 12
>>> print('World', data2)
>>> yield
>>> g = generator()
>>> print(g.__next__())
Python
5
>>> print(g.__next__())
Hello None
12
>>> print(g.__next__())
World None
None
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# send()的效果和next()一样,只是在获取下一个值的时候,send()会给上一个yield的位置传递一个数据
# 第一次必须先使用next()取值,然后使用send()
# 最后一个yield无法接收外部传来的值

>>> def generator():
>>> print('Python')
>>> data1 = yield 5
>>> print('Hello', data1)
>>> data2 = yield 12
>>> print('World', data2)
>>> yield
>>> g = generator()
>>> print(g.__next__())
Python
5
>>> g.send('Fighting!')
Hello Fighting!
>>> g.send('Come on!')
World Come on!


>>> def generator():
>>> print('Python')
>>> data1 = yield 5
>>> print('Hello', data1)
>>> data2 = yield 12
>>> print('World', data2)
>>> yield
>>> g = generator()
>>> print(g.__next__())
Python
5
>>> print(g.__next__())
Hello None
12
>>> g.send('Fighting!')
World Fighting!


>>> def generator():
>>> print('Python')
>>> data1 = yield 5
>>> print('Hello', data1)
>>> data2 = yield 12
>>> print('World', data2)
>>> yield
>>> g = generator()
>>> print(g.__next__())
Python
5
>>> g.send('Fighting!')
Hello Fighting!
>>> print(g.__next__())
World None
None
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
>>> def func():
>>> print(111)
>>> yield 222
>>> yield 333
>>> g = func() # 创建生成器g
>>> g1 = (i for i in g) # 创建生成器g1,来源于g
>>> g2 = (i for i in g1) # 创建生成器g2,来源g1
>>> # list的底层有for循环,for就是一直执行__next__(),所以可以将生成器放到list中
>>> print(list(g)) # 获取g中的数据,这时func()才会被执行,打印111,获取到[222, 333],g完毕
111
[222, 333]
>>> print(list(g1)) # 获取g1中的数据,g1的数据来源是g,但是g已经取完,g1 也就没有数据
[]
>>> print(list(g2)) # 和g1同理
[]


>>> def func():
>>> print(111)
>>> yield 222
>>> yield 333
>>> g = func() # 创建生成器g
>>> g1 = (i for i in g) # 创建生成器g1,来源于g
>>> g2 = (i for i in g1) # 创建生成器g2,来源g1
>>> # 可以用next来验证,其实list就是将内容迭代了转换成了列表
>>> print(next(g))
111
222
>>> print(next(g1))
333
>>> print(next(g2))
#出错,已没有值
Traceback (most recent call last):
print(next(g2))
StopIteration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# yield from
# 把可迭代对象中的每一个数据作为生成器的结果进行返回

>>> def generator():
>>> str1 = 'abc'
>>> str2 = '123'
>>> for i in str1:
>>> yield i
>>> for j in str2:
>>> yield j
>>> g = generator()
>>> for i in g:
>>> print(i, end=' ')
a b c 1 2 3


>>> def generator():
>>> str1 = 'abc'
>>> str2 = '123'
>>> yield from str1
>>> yield from str2
>>> g = generator()
>>> for i in g:
>>> print(i, end=' ')
a b c 1 2 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 预激活生成器的装饰器(通俗的说就是让生成器执行到有yield关键字的地方挂起)

# 动态计算平均值
>>> def init(func):
>>> def inner(*args, **kwargs):
>>> g = func(*args, **kwargs)
>>> g.__next__() # next(g)
>>> return g
>>> return inner
>>> @init
>>> def average():
>>> sum = 0
>>> count = 0
>>> avg = 0
>>> while True:
>>> num = yield avg
>>> sum += num
>>> count += 1
>>> avg = sum / count
>>> avg = average()
>>> print(avg.send(14))
14.0
>>> print(avg.send(20))
17.0
>>> print(avg.send(26))
20.0
>>> print(avg.send(40))
25.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 生成器表达式 用()
# (element 或 operation(element) for element in iterable(for element in iterable...多层for循环,从前往后))
# (element 或 operation(element) for element in iterable(for element in iterable...多层for循环,从前往后) if condition)

# 列表表达式 用[]
# [element 或 operation(element) for element in iterable(for element in iterable...多层for循环,从前往后)]
# [element 或 operation(element) for element in iterable(for element in iterable...多层for循环,从前往后) if condition]

# 列表表达式 用{} 去重功能
# {element 或 operation(element) for element in iterable(for element in iterable...多层for循环,从前往后)}
# {element 或 operation(element) for element in iterable(for element in iterable...多层for循环,从前往后) if condition}


>>> ret1 = [i for i in range(10) if i % 3 == 0]
>>> ret2 = (i for i in range(10) if i % 3 == 0)
>>> print(ret1, type(ret1))
[0, 3, 6, 9] <class 'list'>
>>> print(ret2, type(ret2))
<generator object <genexpr> at 0x000001E788EFE048> <class 'generator'>

四、面向对象

1.概念

通常情况下,在类中定义的所有函数都是对象的绑定方法,对象在调用绑定方法时会自动将自己作为参数传递给方法的第一个参数(默认是self)

1
2
3
4
5
6
7
8
9
10
11
12
>>> class Test:
>>> def __init__(self, name):
>>> self.name = name
>>> def run(self):
>>> return self, self.name
>>> test = Test('Conyyon')
>>> print(test.__init__)
<bound method Test.__init__ of <__main__.Test object at 0x0000021A040089E8>>
>>> print(test.run)
<bound method Test.run of <__main__.Test object at 0x0000021A040089E8>>
>>> print(test.run())
(<__main__.Test object at 0x0000021A040089E8>, 'Conyyon')

当定义了一个class并创建了该类的实例后,可以给该实例动态绑定属性和方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> class Student:
>>> pass
>>> s = Student()
>>> s.name = 'Tom' # 实例动态绑定属性
>>> print(s.name)
Tom
>>> def set_age(self, age): # 定义函数作为实例的方法
>>> self.age = age
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例动态绑定一个方法,另一个实例无法访问
>>> s.set_age(25)
>>> s.age
25

使用__slots__限制绑定的属性
使用__slots__定义的属性仅对当前类实例起作用,对继承的子类不起作用,除非在子类中也定义__slots__,则子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。

1
2
3
4
5
6
7
8
9
>>> class Student:
>>> __slots__ = ('name', 'age')
>>> s = Student()
>>> s.name = 'Tom'
>>> s.age = 25
>>> s.score = 99
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'

组合:一个对象的属性是另外一个类的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> class A:
>>> def __init__(self, birthday):
>>> self.birthday = birthday
>>> class B:
>>> def __init__(self, year, month, day):
>>> self.year = year
>>> self.month = month
>>> self.day = day
>>> b = B(19, 1, 17)
>>> a = A(b)
>>> print(a.birthday.year)
19
>>> print(a.birthday.month)
1
>>> print(a.birthday.day)
17

三大特性:继承、多态、封装

继承

当在父类和子类中都定义了__init__方法时,Python不会自动调用父类的__init__方法,必须显式地在子类中调用它。相反,当没有在子类中定义__init__方法时,会默认调用父类的__init__方法。(方法的重写)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 继承

# 一个类可以被多个类继承、一个类可以继承多个父类
# 新式类:Python3中的类都是新式类,默认继承object,不必显示继承object
# 经典类:Python2中新式类和经典类共存,显式继承父类为新式类,不继承的为经典类

# 单继承
# 派生属性:在子类中定义父类中没有定义的属性
# 派生方法:在子类中定义父类中没有定义的方法
# 子类对象调用属性或方法:子类有,先调用子类的,子类没有,调用父类的,父类没有,报错
# 子类初始化先传入参数调用父类的__init__(self[,...])方法,子类调用父类的属性或方法使用父类名.父类属性或父类名.父类方法(self)



# 多继承
# 新式类中多继承顺序为广度优先
# 经典类中多继承顺序为深度优先
# mro()方法:查看继承关系,只存在于新式类中
# super()方法:Python3不需要传入self参数(Python2 super(类名, self)),不是单纯找父类,而是根据继承顺序(mro方法)查找,只存在于新式类中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Python3新式类多继承(广度优先)
# Python 3.6.6

# 继承关系
# A
# ↗ ↖
# B C
# ↖ ↗
# D
# 广度优先:D、B、C、A
>>> class A:
>>> def func(self):
>>> print('A', end=' ')
>>> class B(A):
>>> def func(self):
>>> super().func()
>>> print('B', end=' ')
>>> class C(A):
>>> def func(self):
>>> super().func()
>>> print('C', end=' ')
>>> class D(B, C):
>>> def func(self):
>>> super().func()
>>> print('D', end=' ')
>>> print(D.mro())
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
>>> d = D()
>>> d.func()
A C B D


# 继承关系
# A
# ↗ ↖
# E F
# ↑ ↑
# B C
# ↖ ↗
# D
# 广度优先:D、B、E、C、F、A
>>> class A:
>>> def func(self):
>>> print('A', end=' ')
>>> class E(A):
>>> def func(self):
>>> super().func()
>>> print('E', end=' ')
>>> class F(A):
>>> def func(self):
>>> super().func()
>>> print('F', end=' ')
>>> class B(E):
>>> def func(self):
>>> super().func()
>>> print('B', end=' ')
>>> class C(F):
>>> def func(self):
>>> super().func()
>>> print('C', end=' ')
>>> class D(B, C):
>>> def func(self):
>>> super().func()
>>> print('D', end=' ')
>>> print(D.mro())
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.E'>, <class '__main__.C'>, <class '__main__.F'>, <class '__main__.A'>, <class 'object'>]
>>> d = D()
>>> d.func()
A F C E B D
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Python2经典类多继承(深度优先)
# Python 2.7.15

# 继承关系
# A
# ↗ ↖
# B C
# ↖ ↗
# D
# 深度优先:D、B、A、C
# 按继承关系手动模拟
>>> class A:
>>> pass
>>> # def func(self): print 'A'
>>> class B(A):
>>> pass
>>> # def func(self): print 'B'
>>> class C(A):
>>> # pass
>>> def func(self): print 'C'
>>> class D(B,C):
>>> pass
>>> # def func(self): print 'D'
>>> d = D()
>>> d.func()
# 依次输出:D B A C


# 继承关系
# A
# ↗ ↖
# E F
# ↑ ↑
# B C
# ↖ ↗
# D
# 深度优先:D、B、E、A、C、F
# 按继承关系手动模拟
class A:
pass
# def func(self): print 'A'
class E(A):
pass
# def func(self): print 'E'
class F(A):
# pass
def func(self): print 'F'
class B(E):
pass
# def func(self): print 'B'
class C(F):
pass
# def func(self): print 'C'
class D(B,C):
pass
# def func(self): print 'D'
d = D()
d.func()
# 依次输出:D B E A C F
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 接口类
# Python没有接口类,使用Class实现接口类
# 子类中实现和父类方法名完全一样的方法(代码规范)
# 不能实例化
# 接口类只强调函数属性的相似性
# 接口类的单继承

>>> from abc import abstractmethod, ABCMeta
>>> class Payment(metaclass=ABCMeta): # 元类,Python3.4之前使用metaclass=ABCMeta,之后直接使用ABC
>>> @abstractmethod
>>> def pay(self, money):
>>> pass # 不必实现这个方法
>>> class Wechat(Payment):
>>> def pay(self, money):
>>> print('微信支付%s元' % money)
>>> class Alipay(Payment):
>>> def pay(self, money):
>>> print('支付宝支付%s元' % money)
>>> class Applepay(Payment):
>>> def pay(self, money):
>>> print('苹果支付%s元' % money)


# 接口类的多继承

>>> from abc import abstractmethod, ABCMeta
>>> class Swim_Animal(metaclass=ABCMeta):
>>> @abstractmethod
>>> def swim(self):
>>> pass
>>> class Walk_Animal(metaclass=ABCMeta):
>>> @abstractmethod
>>> def walk(self):
>>> pass
>>> class Fly_Animal(metaclass=ABCMeta):
>>> @abstractmethod
>>> def fly(self):
>>> pass
>>> class Tiger(Walk_Animal, Swim_Animal):
>>> def swim(self):
>>> pass
>>> def walk(self):
>>> pass
>>> class OldYing(Fly_Animal, Walk_Animal):
>>> def walk(self):
>>> pass
>>> def fly(self):
>>> pass
>>> class Swan(Swim_Animal, Walk_Animal, Fly_Animal):
>>> def swim(self):
>>> pass
>>> def walk(self):
>>> pass
>>> def fly(self):
>>> pass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 抽象类
# Python支持抽象类
# 抽象类就是从一堆类中抽取相同的内容而来,指的是一组类的相似性,包括数据属性和函数属性
# 不能实例化

from abc import ABCMeta, abstractmethod
class File(metaclass=ABCMeta):
@abstractmethod # 定义抽象方法,无需实现功能
def read(self): # 子类必须定义读功能
pass
@abstractmethod # 定义抽象方法,无需实现功能
def write(self): # 子类必须定义写功能
pass
class Txt(File):
def read(self):
print('文本数据的读取方法')
def write(self):
print('文本数据的读取方法')
class Sata(File):
def read(self):
print('硬盘数据的读取方法')
def write(self):
print('硬盘数据的读取方法')
class Process(File):
def read(self):
print('进程数据的读取方法')
def write(self):
print('进程数据的读取方法')

三大特性:继承、多态、封装

多态

1
2
# Python默认支持多态。多态的前提是继承。
# 子类可以继承父类方法(封闭原则),也可重写父类方法(开放原则)

三大特性:继承、多态、封装

封装

1
2
3
4
# 私有静态属性__name、私有属性__self.age、私有方法__func(self)
# 一个下划线开头的实例变量名(如_name)外部可以访问,但按照约定俗成的规定,当看到这样的变量时,意思是“虽然可以被外部访问,但应该被视为私有变量,不要随意访问”。
# 目的:让其类外部无法调用、让属性无法修改、让其不被子类继承(若要在类外部访问和修改可以在类内部增加get和set方法)
# Python并没有一种方法可以完全限制访问私有函数或变量(在类外部使用_类名__名字调用,通过类的__dict__属性查看)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# @property把类中的方法变为属性直接调用(执行以后返回)
# 访问 - setter方法
>>> from math import pi
>>> class Circle:
>>> def __init__(self, radius):
>>> self.radius = radius
>>> @property
>>> def perimeter(self):
>>> return 2*pi*self.radius
>>> @property
>>> def area(self):
>>> return self.radius**2*pi
>>> circle = Circle(3)
>>> print(circle.perimeter)
18.84955592153876
>>> print(circle.area)
28.274333882308138

# 修改 - setter方法
>>> class Student:
>>> @property
>>> def birth(self):
>>> return self._birth
>>> @birth.setter # birth可读写
>>> def birth(self, value):
>>> self._birth = value
>>> @birth.deleter
>>> def birth(self):
>>> del self._birth
>>> @property #age只读
>>> def age(self):
>>> return 2015 - self._birth
>>> s = Student()
>>> s.birth = 1998
>>> print(s.age)
21
>>> del s.birth
>>> print(s.birth)
AttributeError: 'Student' object has no attribute '_birth'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# @staticmathod 类中没有默认参数的方法

>>> class Login:
>>> def __init__(self, name, password):
>>> self.name = name
>>> self.password = password
>>> print(self.name, self.password)
>>> @staticmethod
>>> def get_usr_pwd():
>>> usr = input('用户名 :')
>>> pwd = input('密码 :')
>>> Login(usr, pwd)
>>> Login.get_usr_pwd()
用户名 :root
密码 :123456
root 123456
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# @classmethod 类中的方法只涉及静态属性,可以直接被类调用,不必通过对象调用

>>> class Goods:
>>> __discount = 1
>>> def __init__(self, name, price):
>>> self.name = name
>>> self.__price = price
>>> @property
>>> def price(self):
>>> return self.__price * Goods.__discount
>>> @classmethod
>>> def change_discount(cls, new_discount):
>>> cls.__discount = new_discount
>>> apple = Goods('Apple', 5)
>>> print(apple.price)
5
>>> Goods.change_discount(0.5)
>>> print(apple.price)
2.5

2.反射

应用:根据字符串的形式导入模块、根据字符串的形式去对象(某个模块)中操作其成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# hasattr、getattr、setattr、delattr

>>> class Test:
>>> _name = 'Tom'
>>> @staticmethod
>>> def func():
>>> return 'A test!'
>>> t1 = Test()
>>> print(hasattr(t1, 'age'))
False
>>> print(getattr(t1, '_name'))
Tom
>>> print(getattr(t1, 'name', None))
None
>>> setattr(t1, 'age', 19)
>>> print(t1.age)
19
>>> delattr(t1, 'age')
>>> print(t1.age)
AttributeError: 'Test' object has no attribute 'age'
>>> if hasattr(t1, 'func'):
>>> func1 = getattr(t1, 'func')
>>> func1()
A test!



>>> class Need:
>>> dic = {'username': 'get_username', 'password': 'get_password'}
>>> @staticmethod
>>> def get_username():
>>> print('root')
>>> @staticmethod
>>> def get_password():
>>> print('Denied')
>>> need = Need()
>>> key = input('输入需求:')
>>> if hasattr(need, Need.dic[key]):
>>> func = getattr(Need, need.dic[key])
>>> func()
输入需求:username
root

3.元类

type(arg1, arg2, arg3)函数既可以返回一个对象的类型,又可以创建出新的类。
arg1为class的名称,arg2为继承的父类集合,arg3为class的方法名与函数绑定。
通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描class定义的语法,然后调用type()函数创建出class。

1
2
3
4
5
6
type注释
"""
type(object_or_name, bases, dict)
type(object) -> the object's type
type(name, bases, dict) -> a new type
"""
1
2
3
4
5
6
7
8
9
10
>>> def fn(self, name='world'):
>>> print('Hello, %s.' % name)
>>> Hello = type('Hello', (object,), dict(hello=fn))
>>> h = Hello()
>>> h.hello()
Hello, world.
>>> print(type(Hello))
<class 'type'>
>>> print(type(h))
<class '__main__.Hello'>

除了使用type()动态创建类以外,要控制类的创建行为,还可以使用metaclass。metaclass允许创建类或修改类。可以把类看作是metaclass创建出来的实例。即先定义metaclass,就可以创建类,最后创建实例。(Django ORM)

4.类的内置方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# __new__ 构造方法

# 单例模式

>>> class SingleTon:
>>> def __new__(cls, *args, **kwargs):
>>> if not hasattr(cls, 'instance'):
>>> cls.instance = super().__new__(cls, *args, **kwargs)
>>> return cls.instance
>>> a = SingleTon()
>>> b = SingleTon()
>>> print(a is b)
True
>>> print(id(a) == id(b))
True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# __str__和__repr__、str()和repr()
# __str__()返回用户看到的字符串,__repr__返回程序开发者看到的字符串,是为调试服务的。通常两者的代码都是一样的。
# 如果对象有__str__方法,则返回字符串,如果没有__str__方法,会找本类的__repr__方法,如果本类没有__repr__方法,则找父类的__str__方法。
# 如果对象有__repr__方法,则返回字符串,如果对象没有__repr__方法,则找父类中的__repr__方法。
# __str__ ---> __repr__
# __repr__ ---> __repr__

# 格式化%s、str() ---> __str__
# 格式化%r、repr() ---> __repr__

>>> class Test:
>>> def __str__(self):
>>> return 'str'
>>> def __repr__(self):
>>> return 'repr'
>>> test = Test()
>>> test
repr
>>> print(test)
>>> str
>>> print('%s' % test)
str
>>> print('%r' % test)
repr
1
2
# __del__、del
# 析构函数: 当对象在内存中被释放时,自动触发执行
1
2
# __iter__、iter()
返回一个迭代器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
__getitem__、__setitem__、__delitem__

# 字典键值设置,取值

>>> class Test:
>>> def __init__(self, name):
>>> self.name = name
>>> def __getitem__(self, item):
>>> print('get obj[item]', item, self.__dict__[item])
>>> def __setitem__(self, item, value):
>>> print('set obj[item]', item, value)
>>> self.__dict__[item] = value
>>> def __delitem__(self, item):
>>> print('del obj[item]', item)
>>> self.__dict__.pop(item)
>>> t1 = Test('Tom')
>>> t1['name']
get obj[item] name Tom
>>> t1['age'] = 18
set obj[item] age 18
>>> print(t1.__dict__)
{'name': 'Tom', 'age': 18}
>>> del t1['age']
>>> del t1['name']
>>> print(t1.__dict__)
{}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# __getattribute__、__getattr__、__setattr__、__delattr__

# 当__getattribute__和__getattr__同时出现时,__getattribute__方法一直会被调用,除非当__getattribute__方法出现AttributeError或者在__getattribute__中显式调用__getattr__方法,否则__getattr__不会被执行。
# 若只出现__getattr__方法,则当属性不存在时才会执行,否则若属性存在,则不会执行__getattr__。

>>> class Test:
>>> def __init__(self, name):
>>> self.name = name
>>> def __getattr__(self, item):
>>> print('get obj.key', item)
>>> def __getattribute__(self, item):
>>> print('getattribute obj.key', item)
>>> # Test.__getattr__(self, item)
>>> def __setattr__(self, key, value):
>>> print('set obj.key', key, value)
>>> # self.key = value # 无限递归,一般默认继承父类方法
>>> super().__setattr__(key, value)
>>> def __delattr__(self, item):
>>> print('del obj.key', item)
>>> t1 = Test('Tom')
set obj.key name Tom
>>> t1.__dict__
getattribute obj.key __dict__
>>> t1.name
getattribute obj.key name
>>> t1.name999
getattribute obj.key name999
>>> del t1.name
del obj.key name


>>> class Test:
>>> def __init__(self, name):
>>> self.name = name
>>> def __getattr__(self, item):
>>> print('get obj.key', item)
>>> t1 = Test('Tom')
>>> print(t1.__dict__)
{'name': 'Tom'}
>>> t1.name

>>> t1.name999
get obj.key name999
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# __call__

>>> class Person:
>>> def __init__(self, name):
>>> self.name = name
>>> person = Person('Tom')
>>> person()
TypeError: 'Person' object is not callable

>>> class Person:
>>> def __init__(self, name):
>>> self.name = name
>>> def __call__(self):
>>> for k in self.__dict__:
>>> print(k, self.__dict__[k])
>>> person = Person('Tom')
>>> person()
name Tom

5.元类

1
创建类时先执行type__init__方法,类实例化时执行type__call__方法,__call__方法的返回值就是实例化的对象。(在__call__方法中先执行类的__new__方法生成实例化对象,然后执行__init__方法初始化对象,最后返回对象)

未完待续…