├── PythonAdvanced └── README.md ├── image ├── DBAPI.png └── python.PNG ├── pythonIntermediate ├── if __name__ == '__main__': 原理.md ├── virtualenv 工具.md └── __init__ 和 __new__ 特殊方法.md ├── pythonStandardLibrary └── README.md ├── pythonExercise ├── .editorconfig ├── FluentPython_Code │ ├── Chap3 │ │ ├── set.py │ │ ├── dict.py │ │ ├── dictcomp.py │ │ └── dialcodes.py │ ├── Chap4 │ │ └── bytes.py │ ├── Chap2 │ │ ├── slice.py │ │ ├── tuple.py │ │ ├── deque.py │ │ ├── numpyTest.py │ │ ├── sort.py │ │ ├── namedtuple.py │ │ ├── list_comprehension.py │ │ ├── generator_expression.py │ │ └── bisect.py │ ├── Chap5 │ │ └── higherOrderFunc.py │ └── Chap1 │ │ ├── Vector.py │ │ └── FrenchDeck.py ├── python3_MySQL │ ├── README.md │ ├── connectMySQL.py │ ├── deleteMySQL.py │ ├── selectMySQL.py │ ├── insertMySQL.py │ ├── createMySQL.py │ └── updateMySQL.py └── Basic │ ├── function.py │ ├── closure.py │ ├── operator.py │ └── sequence.py ├── README.md ├── Python 入门.md ├── Python 高级.md └── Python 进阶.md /PythonAdvanced/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /image/DBAPI.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steveLauwh/Python/HEAD/image/DBAPI.png -------------------------------------------------------------------------------- /image/python.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/steveLauwh/Python/HEAD/image/python.PNG -------------------------------------------------------------------------------- /pythonIntermediate/if __name__ == '__main__': 原理.md: -------------------------------------------------------------------------------- 1 | ## if __name__ == '__main__': 原理 2 | -------------------------------------------------------------------------------- /pythonStandardLibrary/README.md: -------------------------------------------------------------------------------- 1 | # The Python Standard Library 2 | 3 | [官方文档](https://docs.python.org/3/library/index.html) 4 | -------------------------------------------------------------------------------- /pythonExercise/.editorconfig: -------------------------------------------------------------------------------- 1 | # top-most EditorConfig file 2 | root = true 3 | 4 | # all files 5 | [*] 6 | indent_style = tab 7 | indent_size = 4 8 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap3/set.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | '''Chap3 5 | set 集合 6 | ''' 7 | s = {1} 8 | 9 | s.add(2) 10 | 11 | print(s) 12 | 13 | s.pop() 14 | 15 | print(s) 16 | 17 | s.clear() 18 | 19 | print(s) -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap4/bytes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | '''Chap4 5 | 使用数组中的原始数据初始化 bytes 对象 6 | ''' 7 | import array 8 | 9 | numbers = array.array('h', [-2, -1, 0, 1, 2]) 10 | 11 | octets = bytes(numbers) 12 | 13 | print(octets) -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap2/slice.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 2 5 | 切片:list, tuple, str 都支持切片操作. 6 | ''' 7 | l = list(range(10)) 8 | 9 | print(l) 10 | 11 | l[2:5] = [20, 30] 12 | 13 | print(l) 14 | 15 | del l[5:7] 16 | 17 | print(l) 18 | 19 | l[3::2] = [11, 22] 20 | 21 | print(l) 22 | 23 | l[2:5] = [100] 24 | 25 | print(l) 26 | -------------------------------------------------------------------------------- /pythonExercise/python3_MySQL/README.md: -------------------------------------------------------------------------------- 1 | ## 使用 Python3 操作 MySQL 数据库 2 | 3 | Python 操作 MySQL 数据库需要使用驱动,PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库。 4 | 5 | **1. 安装 PyMySQL** 6 | 7 | 安装:`pip install PyMySQL` 8 | 9 | 查看 PyMySQL 安装是否成功:`pip show PyMySQL` 10 | 11 | **2. MySQL 数据库安装** 12 | 13 | **3. 使用 Python 对 MySQL 数据库表的增删查改操作** 14 | 15 | ![](https://github.com/steveLauwh/Python/raw/master/image/DBAPI.png) 16 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap3/dict.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 3 5 | 字典 dict,提供多种构造方法 6 | ''' 7 | a = dict(one = 1, two = 2, three = 3) 8 | 9 | b = {'one': 1, 'two': 2, 'three': 3} 10 | 11 | c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) 12 | 13 | d = dict([('two', 2), ('one', 1), ('three', 3)]) 14 | 15 | e = dict({'three': 3, 'one': 1, 'two': 2}) 16 | 17 | print(a == b == c == d == e) 18 | 19 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap2/tuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 2 5 | 元组:不仅是不可变的列表,还可以用于没有字段名的记录。 6 | ''' 7 | lax_corrdinates = (33.9425, -118.408056) 8 | 9 | city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014) 10 | 11 | traveler_ids = [('USA', '31195855'), ('BRA', 'CE342567'), ('ESP', 'XDA205856')] 12 | 13 | for passport in sorted(traveler_ids): 14 | print('%s/%s' %passport) 15 | 16 | # “_” 占位符 17 | for county, _ in traveler_ids: 18 | print(county) 19 | 20 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap2/deque.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 2 5 | collections.deque 类(双向队列)是一个线程安全、可以快速从两端添加或者删除元素的数据类型。 6 | ''' 7 | from collections import deque 8 | 9 | dq = deque(range(10), maxlen = 10) 10 | 11 | print(dq) 12 | 13 | dq.rotate(3) 14 | 15 | print(dq) 16 | 17 | dq.rotate(-4) 18 | 19 | print(dq) 20 | 21 | dq.appendleft(-1) 22 | 23 | print(dq) 24 | 25 | dq.extend([11, 22, 33]) 26 | 27 | print(dq) 28 | 29 | dq.extendleft([10, 20, 30, 40]) 30 | 31 | print(dq) 32 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap2/numpyTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 2 5 | numpy 库 6 | ''' 7 | import numpy as ny 8 | 9 | # 新建 0-11 的整数 numpy.ndarray 10 | a = ny.arange(12) 11 | 12 | print(a) 13 | 14 | print(type(a)) 15 | 16 | # 数组的维度 17 | print(a.shape) 18 | 19 | # 数组变成二维,打印 20 | a.shape = 3, 4 21 | 22 | print(a) 23 | 24 | # 打印第 2 行 25 | print(a[2]) 26 | 27 | # 打印第 2 行第 1 列元素 28 | print(a[2, 1]) 29 | 30 | # 打印第 1 列 31 | print(a[:, 1]) 32 | 33 | # 行和列交换 34 | print(a.transpose()) 35 | -------------------------------------------------------------------------------- /pythonIntermediate/virtualenv 工具.md: -------------------------------------------------------------------------------- 1 | ## virtualenv 工具 2 | 3 | virtualenv: A tool for creating isolated 'virtual' python environments. [Github](https://github.com/pypa/virtualenv) 4 | 5 | 使用 virtualenv 工具可以为每个应用创建一个独立的 Python 运行环境(虚拟)。 6 | 7 | Python3 环境下安装 virtualenv 工具: 8 | 9 | ``` 10 | # 安装 virtualenv 11 | pip3 install virtualenv 12 | 13 | # 创建一个独立的 Python 虚拟运行环境 venv 14 | virtualenv --no-site-packages venv 15 | 16 | # 进入一个虚拟运行环境,然后就可以在这个虚拟环境安装各种第三方包 17 | source venv/bin/activate 18 | 19 | # 退出当前虚拟环境 20 | deactivate 21 | ``` 22 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap2/sort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 2 5 | list.sort 方法和内置函数 sorted 6 | 7 | list.sort 方法会就地排序列表,不会把原列表复制一份。 8 | 9 | 内置函数 sorted 会新建一个列表作为返回值。 10 | ''' 11 | fruits = ['grape', 'raspberry', 'apple', 'banana'] 12 | 13 | print(sorted(fruits)) 14 | 15 | print(fruits) 16 | 17 | print(sorted(fruits, reverse = True)) 18 | 19 | print(sorted(fruits, key = len)) 20 | 21 | print(sorted(fruits, key = len, reverse = True)) 22 | 23 | print(fruits) 24 | 25 | print(fruits.sort()) 26 | 27 | print(fruits) 28 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap2/namedtuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 2 5 | 具名元组:collections.namedtuple 是一个工厂函数,它可以用来构建一个带字段名的元组和一个有名字的类。 6 | ''' 7 | from collections import namedtuple 8 | 9 | # 具名数组两个参数:类名,类的各个字段的名字 10 | City = namedtuple('City', 'name country population coordinates') 11 | 12 | tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) 13 | 14 | print(tokyo) 15 | 16 | print(tokyo.population) 17 | 18 | print(tokyo.coordinates) 19 | 20 | print(tokyo[1]) 21 | 22 | # _fields 属性是一个包含这个类所有字段名称的元组 23 | print(City._fields) 24 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap3/dictcomp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 3 5 | 字典推导 6 | ''' 7 | DIAL_CODES = [ 8 | (86, 'China'), 9 | (91, 'India'), 10 | (1, 'United States'), 11 | (62, 'Indonesia'), 12 | (55, 'Brazil'), 13 | (92, 'Pakistan'), 14 | (880, 'Bangladesh'), 15 | (234, 'Nigeria'), 16 | (7, 'Russia'), 17 | (81, 'Japan') 18 | ] 19 | 20 | country_code = {country: code for code, country in DIAL_CODES} 21 | 22 | print(country_code) 23 | 24 | country_code = {code: country.upper() for code, country in DIAL_CODES} 25 | 26 | print(country_code) 27 | -------------------------------------------------------------------------------- /pythonExercise/Basic/function.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # 全局变量 4 | a = 1 5 | 6 | def change_integer(a): 7 | a = 2 # 局部变量 8 | return a 9 | 10 | print(change_integer(a), a) 11 | 12 | def Max(val1, val2): 13 | return max(val1, val2) # Built-in 14 | 15 | print(Max(100, 90)) 16 | 17 | # 可变对象 18 | list1 = [1, 'Hello', 3] 19 | 20 | def change_list(list1): 21 | list1[2] = 5 22 | return list1 23 | 24 | print(change_list(list1), list1) 25 | 26 | # 判断闰年 27 | def isLeap(year): 28 | return (year%400 == 0 or (year%4 == 0 and year%100 != 0)) 29 | 30 | print(isLeap(2018)) 31 | -------------------------------------------------------------------------------- /pythonExercise/python3_MySQL/connectMySQL.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # host = localhost 4 | # database: example1 5 | # user: root 6 | # password: 123456 7 | # 查询 MySQL 版本 8 | 9 | import pymysql.cursors 10 | 11 | # 打开数据库连接 12 | connection = pymysql.connect(host = 'localhost', 13 | user = 'root', 14 | password = '123456', 15 | db = 'example1') 16 | 17 | # 使用 cursor() 方法创建一个游标对象 cursor 18 | cursor = connection.cursor() 19 | 20 | # 使用 execute() 方法执行 SQL 查询 21 | cursor.execute('SELECT VERSION()') 22 | 23 | # 使用 fetchone() 方法获取单条数据 24 | data = cursor.fetchone() 25 | 26 | print('Database version : %s' % data) 27 | 28 | # 关闭数据库连接 29 | connection.close() 30 | -------------------------------------------------------------------------------- /pythonExercise/Basic/closure.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | ########################## 5 | def foo(): 6 | print('I am foo') 7 | 8 | def bar(): 9 | print('I am bar') 10 | 11 | foo.bar = bar 12 | foo.bar() 13 | ########################## 14 | def f(j): 15 | def g(): # g 就是闭包函数 16 | return j*j 17 | return g 18 | 19 | g1 = f(2) 20 | 21 | print(g1.__closure__) # __closure__ 就是 enclosing作用域 22 | 23 | print(g1()) 24 | ########################## 25 | def dec(func): 26 | def wrapper(): 27 | func() 28 | return wrapper 29 | 30 | def sum(): 31 | print('sum') 32 | 33 | foo = dec(sum) 34 | 35 | foo() 36 | 37 | print(foo.__closure__) 38 | ########################## -------------------------------------------------------------------------------- /pythonExercise/Basic/operator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | print(1+1) 4 | 5 | print(1-1) 6 | 7 | print(2*2) 8 | 9 | print(3/4) 10 | 11 | print(3//4) 12 | 13 | print(3**2) 14 | 15 | print(10%4) 16 | 17 | print(1==1) 18 | 19 | print(1!=1) 20 | 21 | print(1==True) 22 | 23 | print(1==False) 24 | 25 | print(1<2) 26 | 27 | print(1>3) 28 | 29 | print(1<=5) 30 | 31 | print(1>=0) 32 | 33 | print(1 in [1,3,5,6]) 34 | 35 | print(1 and 0) 36 | 37 | print(1 or 0) 38 | 39 | print(True and False) 40 | 41 | print(True or False) 42 | 43 | print(not False) 44 | 45 | print(not True) 46 | 47 | print(not 1==1) 48 | 49 | print(not 1==0) 50 | 51 | print(not 1==-1) 52 | 53 | a = 20 54 | 55 | b = 20 56 | 57 | print(a is b) 58 | -------------------------------------------------------------------------------- /pythonExercise/python3_MySQL/deleteMySQL.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # host = localhost 4 | # database: example1 5 | # user: root 6 | # password: 123456 7 | # table: students 8 | # 向 students 表删除记录 9 | 10 | import pymysql.cursors 11 | 12 | # 打开数据库连接 13 | connection = pymysql.connect(host = 'localhost', 14 | user = 'root', 15 | password = '123456', 16 | db = 'example1', 17 | charset = 'utf8mb4') 18 | 19 | try: 20 | # 查询操作 21 | with connection.cursor() as cursor: 22 | sql = "DELETE FROM students WHERE name = 'steve'" 23 | cursor.execute(sql) 24 | connection.commit() 25 | print('delete success') 26 | except Exception as e: 27 | print("Error to delete:", e) 28 | finally: 29 | connection.close() 30 | -------------------------------------------------------------------------------- /pythonIntermediate/__init__ 和 __new__ 特殊方法.md: -------------------------------------------------------------------------------- 1 | ## `__init__ 和 __new__` 特殊方法 2 | 3 | `__new__` 特殊方法是在类创建的时候调用,第一个参数是 cls,用来控制类的创建行为,属于类级别,最先调用。 4 | 5 | `__init__` 特殊方法是类实例化过程中,进行初始化属性,属于实例级别。 6 | 7 | ```python 8 | #!/usr/bin/env python3 9 | # -*- coding: utf-8 -*- 10 | 11 | class Person(object): 12 | def __new__(cls, name, age): 13 | print('__new__ called') 14 | return super(Person, cls).__new__(cls) 15 | def __init__(self, name, age): 16 | print('__init__ called') 17 | self.name = name 18 | self.age = age 19 | def __str__(self): 20 | return 'Person: %s, %s' %(self.name, self.age) 21 | 22 | if __name__ == '__main__': 23 | p = Person('CC', 20) 24 |   print(p) 25 | ``` 26 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap2/list_comprehension.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 2 5 | 列表(list)是一个可变的序列,并且能同时存放不同类型的元素 6 | 7 | 列表推导(list comprehension):生成列表 8 | 9 | 生成器表达式(generator expression):背后遵守迭代器协议,可以逐个地产出元素 10 | ''' 11 | symbols = '$¢£¥€¤' 12 | 13 | codes = [ord(symbol) for symbol in symbols] 14 | 15 | print(codes) 16 | 17 | ####################################### 18 | x = 'ABC' 19 | 20 | dummy = [ord(x) for x in x] 21 | 22 | print(x, dummy) 23 | 24 | ####################################### 25 | colors = ['black', 'white'] 26 | 27 | sizes = ['S', 'M', 'L'] 28 | 29 | tshirts = [(color, size) for color in colors for size in sizes] 30 | 31 | print(tshirts) 32 | 33 | ####################################### 34 | 35 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap5/higherOrderFunc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | '''Chap5 5 | 高阶函数 6 | ''' 7 | fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] 8 | 9 | print(sorted(fruits, key=len)) 10 | 11 | ################################################################ 12 | def factorial(n): 13 | return 1 if n < 2 else n * factorial(n-1) 14 | 15 | fact = factorial 16 | 17 | # 构建 0! 到 5! 的一个阶乘列表 18 | print(list(map(fact, range(6)))) 19 | 20 | # 使用列表推导执行相同的操作 21 | print([fact(n) for n in range(6)]) 22 | 23 | # 使用 map 和 filter 计算直到 5! 的奇数阶乘列表 24 | print(list(map(factorial, filter(lambda n: n % 2, range(6))))) 25 | 26 | # 使用列表推导做相同的工作,换掉 map 和 filter,并避免了使用 lambda 表达式 27 | print([factorial(n) for n in range(6) if n % 2]) -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap2/generator_expression.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 2 5 | 生成器表达式(generator expression):背后遵守迭代器协议,可以逐个地产出元素 6 | 7 | 作用:避免额外的内存占用 8 | ''' 9 | symbols = '$¢£¥€¤' 10 | 11 | # 用生成器表达式初始化元组 12 | codes = tuple(ord(symbol) for symbol in symbols) 13 | 14 | print(codes) 15 | 16 | ####################################### 17 | import array 18 | 19 | # 用生成器表达式初始化数组 20 | arr = array.array('I', (ord(symbol) for symbol in symbols)) 21 | 22 | print(arr) 23 | 24 | ####################################### 25 | colors = ['black', 'white'] 26 | 27 | sizes = ['S', 'M', 'L'] 28 | 29 | for tshirts in ('%s %s' % (color, size) for color in colors for size in sizes): 30 | print(tshirts) 31 | 32 | ####################################### 33 | 34 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap3/dialcodes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | '''Chap3 5 | dict 字典, 将同样的数据以不同的顺序添加到 3 个字典里 6 | ''' 7 | DIAL_CODES = [ 8 | (86, 'China'), 9 | (91, 'India'), 10 | (1, 'United States'), 11 | (62, 'Indonesia'), 12 | (55, 'Brazil'), 13 | (92, 'Pakistan'), 14 | (880, 'Bangladesh'), 15 | (234, 'Nigeria'), 16 | (7, 'Russia'), 17 | (81, 'Japan') 18 | ] 19 | 20 | # 创建 d1 的时候,数据元组的顺序是按照国家的人口排名来决定的。 21 | d1 = dict(DIAL_CODES) 22 | 23 | print('d1: ', d1.keys()) 24 | 25 | # 创建 d2 的时候,数据元组的顺序是按照国家的电话区号来决定的。 26 | d2 = dict(sorted(DIAL_CODES)) 27 | 28 | print('d2: ', d2.keys()) 29 | 30 | # 创建 d3 的时候,数据元组的顺序是按照国家名字的英文拼写来决定的。 31 | d3 = dict(sorted(DIAL_CODES, key=lambda x:x[1])) 32 | 33 | print('d3: ', d3.keys()) 34 | 35 | assert d1 == d2 and d2 == d3 36 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap2/bisect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | '''Chap 2 5 | bisect(haystack, needle) 6 | 利用二分查找算法来在有序序列中查找或插入元素。 7 | ''' 8 | import bisect 9 | import sys 10 | 11 | HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30] 12 | NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31] 13 | ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}' 14 | 15 | def demo(bisect_fn): 16 | for needle in reversed(NEEDLES): 17 | position = bisect_fn(HAYSTACK, needle) 18 | offset = position * ' |' 19 | print(ROW_FMT.format(needle, position, offset)) 20 | 21 | if __name__ == '__main__': 22 | if sys.argv[-1] == 'left': 23 | bisect_fn = bisect.bisect_left 24 | else: 25 | bisect_fn = bisect.bisect 26 | print('DEMO:', bisect_fn.__name__) 27 | print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK)) 28 | demo(bisect_fn) 29 | -------------------------------------------------------------------------------- /pythonExercise/python3_MySQL/selectMySQL.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # host = localhost 4 | # database: example1 5 | # user: root 6 | # password: 123456 7 | # table: students 8 | # 向 students 表查询记录 9 | 10 | import pymysql.cursors 11 | 12 | # 打开数据库连接 13 | connection = pymysql.connect(host = 'localhost', 14 | user = 'root', 15 | password = '123456', 16 | db = 'example1', 17 | charset = 'utf8mb4') 18 | 19 | try: 20 | with connection.cursor() as cursor: 21 | sql = "SELECT * FROM students WHERE score > 70" 22 | cursor.execute(sql) 23 | result = cursor.fetchall() #获取符合条件的多条数据 24 | for row in result: 25 | id = row[0] 26 | name = row[1] 27 | score = row[2] 28 | print('id = %d, name = %s, score = %d' % (id, name, score)) 29 | except Exception as e: 30 | print("Error to select:", e) 31 | finally: 32 | connection.close() 33 | -------------------------------------------------------------------------------- /pythonExercise/python3_MySQL/insertMySQL.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # host = localhost 4 | # database: example1 5 | # user: root 6 | # password: 123456 7 | # table: students 8 | # 向 students 表插入数据 9 | 10 | import pymysql.cursors 11 | 12 | # 打开数据库连接 13 | connection = pymysql.connect(host = 'localhost', 14 | user = 'root', 15 | password = '123456', 16 | db = 'example1', 17 | charset = 'utf8mb4') 18 | 19 | try: 20 | with connection.cursor() as cursor: 21 | # SQL 插入语句 22 | sql = "INSERT INTO students (name, score) VALUES ('steve', 99)" 23 | cursor.execute(sql) 24 | 25 | # 提交到数据库执行 26 | connection.commit() 27 | 28 | with connection.cursor() as cursor: 29 | sql = "SELECT id, name FROM students WHERE score=99" 30 | cursor.execute(sql) 31 | result = cursor.fetchone() # 获取单条数据 32 | print(result) 33 | 34 | finally: 35 | connection.close() 36 | -------------------------------------------------------------------------------- /pythonExercise/python3_MySQL/createMySQL.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # host = localhost 4 | # database: example1 5 | # user: root 6 | # password: 123456 7 | # 创建 students 表 8 | 9 | import pymysql.cursors 10 | 11 | # 打开数据库连接 12 | connection = pymysql.connect(host = 'localhost', 13 | user = 'root', 14 | password = '123456', 15 | db = 'example1') 16 | 17 | try: 18 | # 上下文管理器 19 | with connection.cursor() as cursor: 20 | # 使用 execute() 方法执行 SQL 语句,如果表存在则删除 21 | cursor.execute('DROP TABLE IF EXISTS students') 22 | 23 | # 使用预处理语句创建表 24 | sql = """CREATE TABLE `students` ( 25 | `id` int(11) NOT NULL AUTO_INCREMENT, 26 | `name` varchar(50) NOT NULL, 27 | `score` int, 28 | PRIMARY KEY (`id`) 29 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1""" 30 | 31 | cursor.execute(sql) 32 | 33 | print('Create students success') 34 | finally: 35 | connection.close() 36 | 37 | 38 | -------------------------------------------------------------------------------- /pythonExercise/python3_MySQL/updateMySQL.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # host = localhost 4 | # database: example1 5 | # user: root 6 | # password: 123456 7 | # table: students 8 | # 向 students 表更新记录 9 | 10 | import pymysql.cursors 11 | 12 | # 打开数据库连接 13 | connection = pymysql.connect(host = 'localhost', 14 | user = 'root', 15 | password = '123456', 16 | db = 'example1', 17 | charset = 'utf8mb4') 18 | 19 | try: 20 | # 查询操作 21 | with connection.cursor() as cursor: 22 | sql = "SELECT * FROM students WHERE score > 70" 23 | cursor.execute(sql) 24 | result = cursor.fetchall() 25 | for row in result: 26 | print(row) 27 | 28 | # 更新操作 29 | with connection.cursor() as cursor: 30 | sql = "UPDATE students SET score = score + 1 WHERE name = 'steve'" 31 | cursor.execute(sql) 32 | connection.commit() 33 | print('Update success') 34 | 35 | except Exception as e: 36 | print("Error to update:", e) 37 | finally: 38 | connection.close() 39 | -------------------------------------------------------------------------------- /pythonExercise/Basic/sequence.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # tuple(元组) 4 | 5 | tuple1 = (11, 2, 9, 1) 6 | 7 | print(tuple1, type(tuple1)) 8 | 9 | tuple2 = ('H', 2, 1.1, False) 10 | 11 | print(tuple2, type(tuple2)) 12 | 13 | print(tuple1[3], tuple2[0]) 14 | 15 | print(tuple1[:4]) 16 | 17 | print(tuple1[2:4]) 18 | 19 | # 字符串也是 tuple 20 | 21 | str1 = 'Hello' 22 | 23 | print(str1[2:4]) 24 | 25 | #str1[0] = 1 26 | #print(str1) 27 | 28 | # list(表) 29 | 30 | list1 = ['a', 1.2, 4, True] 31 | 32 | print(list1, type(list1)) 33 | 34 | list1[0] = 1 35 | 36 | print(list1) 37 | 38 | print(list1[-1]) 39 | 40 | # tuple 中包含 list 41 | 42 | tuple3 = (tuple1,list1) 43 | 44 | print(tuple3, type(tuple3)) 45 | 46 | tuple3[1][2] = 'H' # tuple中存储的是固定的list地址,但list中的元素是可变的 47 | 48 | print(tuple3, type(tuple3)) 49 | 50 | # list 中包含 tuple 51 | 52 | list2 = [tuple1, list1] 53 | 54 | print(list2, type(list2)) 55 | 56 | print(list2[0]) 57 | 58 | print(list2[1]) 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap1/Vector.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | ''' Chap 1 5 | 一个简单的二维向量类 6 | 7 | 模拟数值类型 8 | ''' 9 | 10 | from math import hypot 11 | 12 | class Vector: 13 | def __init__(self, x=0, y=0): 14 | self.x = x 15 | self.y = y 16 | 17 | def __repr__(self): 18 | return 'Vector<%r, %r>' % (self.x, self.y) 19 | 20 | def __abs__(self): 21 | return hypot(self.x, self.y) 22 | 23 | def __bool__(self): 24 | return bool(self.x or self.y) 25 | 26 | def __add__(self, other): 27 | x = self.x + other.x 28 | y = self.y + other.y 29 | return Vector(x, y) 30 | 31 | def __sub__(self, other): 32 | x = self.x - other.x 33 | y = self.y - other.y 34 | return Vector(x, y) 35 | 36 | def __mul__(self, scalar): 37 | return Vector(self.x * scalar, self.y * scalar) 38 | 39 | # test 40 | v = Vector(3, 4) 41 | v2 = Vector(4, 5) 42 | 43 | print(v) 44 | 45 | print(abs(v)) 46 | 47 | print(bool(v)) 48 | 49 | print(v + v2) 50 | 51 | print(v * 3) 52 | 53 | print(v - v2) 54 | -------------------------------------------------------------------------------- /pythonExercise/FluentPython_Code/Chap1/FrenchDeck.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding:utf-8 3 | 4 | """ Chap 1 5 | 一摞有序的纸牌 6 | 集合类 collections-namedtuple 7 | 8 | 特殊方法(双下方法) 9 | """ 10 | from collections import namedtuple 11 | from random import choice 12 | 13 | Card = namedtuple('Card', ['rank', 'suit']) 14 | 15 | class FrenchDeck: 16 | ranks = [str(n) for n in range(2, 11)] + list('JQKA') 17 | suits = 'spades diamods clubs hearts'.split() 18 | 19 | def __init__(self): 20 | self._cards = [Card(rank, suit) for rank in self.ranks 21 | for suit in self.suits] 22 | 23 | def __len__(self): 24 | return len(self._cards) 25 | 26 | def __getitem__(self, position): 27 | return self._cards[position] 28 | 29 | #beer_card = Card('7', 'diamods') 30 | 31 | #print(beer_card) 32 | 33 | deck = FrenchDeck() 34 | 35 | #print(len(deck)) 36 | 37 | #print(deck[0]) 38 | 39 | #print(deck[-1]) 40 | 41 | #print(choice(deck)) 42 | 43 | #print(choice(deck)) 44 | 45 | #print(choice(deck)) 46 | 47 | #print(deck[:3]) 48 | 49 | #print(deck[12::13]) 50 | 51 | # for card in deck: 52 | # print(card) 53 | 54 | # for card in reversed(deck): 55 | # print(card) 56 | 57 | #print(Card('Q', 'hearts') in deck) 58 | 59 | #print(Card('A', 'beats') in deck) 60 | 61 | suit_values = dict(spades=3, hearts=2, diamods=1, clubs=0) 62 | def spades_high(card): 63 | rank_value = FrenchDeck.ranks.index(card.rank) 64 | return rank_value * len(suit_values) + suit_values[card.suit] 65 | 66 | for card in sorted(deck, key=spades_high): 67 | print(card) 68 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python 2 | 3 | ![](https://github.com/steveLauwh/Python/raw/master/image/python.PNG) 4 | 5 | Python 3 版本 6 | 7 | ## 目录 8 | 9 | * [Python 入门](https://github.com/steveLauwh/Python/blob/master/Python%20%E5%85%A5%E9%97%A8.md)  10 | * [Python 进阶](https://github.com/steveLauwh/Python/blob/master/Python%20%E8%BF%9B%E9%98%B6.md) 11 | + [`__init__ 和 __new__ 特殊方法`](https://github.com/steveLauwh/Python/blob/master/pythonIntermediate/__init__%20%E5%92%8C%20__new__%20%E7%89%B9%E6%AE%8A%E6%96%B9%E6%B3%95.md) 12 | + [virtualenv 工具](https://github.com/steveLauwh/Python/blob/master/pythonIntermediate/virtualenv%20%E5%B7%A5%E5%85%B7.md) 13 | + [`if __name__ == '__main__': 原理`](https://github.com/steveLauwh/Python/blob/master/pythonIntermediate/if%20__name__%20%3D%3D%20'__main__':%20%E5%8E%9F%E7%90%86.md) 14 | * [Python 高级](https://github.com/steveLauwh/Python/blob/master/Python%20%E9%AB%98%E7%BA%A7.md) 15 | * [Python 标准库](https://github.com/steveLauwh/Python/tree/master/pythonStandardLibrary) 16 | * [Python Examples](https://github.com/steveLauwh/Python/tree/master/pythonExercise) 17 | 18 | ## 收集 19 | 20 | * [你的Python到底有没有入门?来做个60秒小测试吧](https://zhuanlan.zhihu.com/p/28075008) 21 | * [Google Python Style Guide](http://google.github.io/styleguide/pyguide.html) 22 | * [Google Python 风格指南](http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/contents/) 23 | 24 | ## 参考资料 25 | 26 | * [Python 官网文档](https://docs.python.org/3/) 27 | * [知乎周刊-编程小白学 Python](https://www.zhihu.com/pub/reader/19550511/chapter/911344090845691904) 28 | * [Vamei-Python 快速教程](http://www.cnblogs.com/vamei/archive/2012/09/13/2682778.html) 29 | * [廖雪峰-Pthon3 教程](https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000) 30 | * [Python3 入门机器学习](https://github.com/liuyubobobo/Play-with-Machine-Learning-Algorithms) 31 | -------------------------------------------------------------------------------- /Python 入门.md: -------------------------------------------------------------------------------- 1 | # Python 入门 2 | 3 | python 一切皆对象。 4 | 5 | ## 运行 6 | 7 | shell 终端,设置环境变量 8 | 9 | ``` 10 | $ PATH=$PATH:/usr/local/python3/bin/python3 11 | $ python3 --version 12 | ``` 13 | 14 | * 命令行方式:在 Linux 终端,输入 python 或 ipython 进入 15 | * 程序方式:例如写一个 hello.py 文件,执行 `python hello.py` 16 | * 脚本方式:修改文件为可执行文件,`python +x hello.py`;然后执行 `./hello.py` 17 | 18 | ```python 19 | #!/usr/bin/env python3 20 | 21 | print('Hello, World!') 22 | ``` 23 | 24 | ## 数据类型 25 | 26 | Python3 中有六个标准的数据类型: 27 | 28 | * number(数字) 29 | * string(字符串) 30 | * list(列表) 31 | * tuple(元组) 32 | * set(集合) 33 | * dictionary(字典) 34 | 35 | ### number(数字) 36 | 37 | * int, float, bool, complex 四种基本类型,用于存储数值 38 | * 内置函数 type(), 用以查询变量的类型 39 | 40 | 1.变量为什么不需要声明类型? 41 | 42 | 2.变量怎么回收? 43 | 44 | 3.内置函数 type() 与 isinstance() 区别 45 | 46 | type() 不会认为子类是一种父类类型,isinstance() 认为子类是一种父类类型。 47 | 48 | ```python 49 | class A: 50 | pass 51 | 52 | class B(A): 53 | pass 54 | 55 | isinstance(A(), A) # returns True 56 | type(A()) == A # returns True 57 | isinstance(B(), A) # returns True 58 | type(B()) == A # returns False 59 | ``` 60 | 61 | ### string(字符串) 62 | 63 | ```python 64 | #!/usr/bin/env python3 65 | 66 | str1 = 'Hello' 67 | 68 | print(str1[0]) 69 | ``` 70 | * 字符串需要用单引号 ' ' 或双引号 " " 括起来 71 | * 字符串也是一种特殊的元组。不能改变字符串中的某个元素的值 72 | 73 | ### list (列表) 74 | 75 | ```python 76 | #!/usr/bin/env python3 77 | 78 | list1 = [True, 1, 'Hello'] 79 | 80 | print(list1) 81 | ``` 82 | * list 的数据项可以不同类型 83 | * list 的各个元素可以改变 84 | * list 是使用 [ ] 方括号包含各个数据项 85 | 86 | ### tuple (元组) 87 | 88 | ```python 89 | #!/usr/bin/env python3 90 | 91 | tuple1 = (True, 1, 'Hello') 92 | 93 | print(tuple1) 94 | ``` 95 | * tuple 是使用 ( ) 小括号包含各个数据项 96 | * tuple 与 list 的唯一区别是 tuple 的元素是不能修改,而 list 的元素可以修改 97 | 98 | ### set(集合) 99 | 100 | 类似 C++ STL unordered_set 101 | 102 | * set 是一个无序不重复元素的序列 103 | * 使用大括号 { } 或者 set() 函数创建集合 104 | * 用 set() 创建一个空集合 105 | * 使用 set 可以去重 106 | 107 | ```python 108 | #!/usr/bin/env python3 109 | 110 | set1 = {'me', 'you', 'she', 'me'} 111 | 112 | print(set1) 113 | ``` 114 | 1.怎么理解 tuple, list 是有序的序列,而 set 是无序的序列 115 | 116 | tuple 或 list 的定义元素顺序和输出一样,而 set 不是。 117 | 118 | ### dictionary(字典) 119 | 120 | 类似 C++ STL hash_map 121 | 122 | * 字典的每个元素是键值对,无序的对象集合 123 | * 字典是可变容器模型,且可存储任意类型对象 124 | * 字典可以通过键来引用,键必须是唯一的,但值则不必 125 | * 字典是使用 { } 大括号包含键值对 126 | * 创建空字典使用 { } 127 | 128 | ```python 129 | #!/usr/bin/env python3 130 | 131 | dict1 = {'name': 'steve', 'age': 18} 132 | 133 | print(dict1) 134 | ``` 135 | 136 | ## 运算符 137 | 138 | 1.返回 True 和 False 的问题? 139 | 140 | 数字 0 是 False,其他都是 True。 141 | 142 | 字符 "" 是 False,其他都是 True。 143 | 144 | 2.is 和 == 区别? 145 | 146 | `is` 用于判断两个变量引用对象是否为同一个, `==` 用于判断引用变量的值是否相等。 147 | 148 | 判断两个标识符是否引用同一个对象:is, is not 149 | 150 | 3.逻辑运算符 151 | 152 | and, or, not 153 | 154 | 4.成员运算符 155 | 156 | 判断是否在指定的序列:in, not in 157 | 158 | ## 条件控制 159 | 160 | ```python 161 | if condition_1: 162 | statement_block_1 163 | elif condition_2: 164 | statement_block_2 165 | else: 166 | statement_block_3 167 | ``` 168 | python 中没有 `switch ... case` 语句。 169 | 170 | ## 循环 171 | 172 | for 循环 173 | 174 | ```python 175 | for 元素 in 序列: 176 | statement 177 | ``` 178 | 179 | for 循环使用 else 语句 180 | 181 | ```python 182 | # 如果 else 语句和 for 循环语句一起使用,else 语句块只在 for 循环正常终止时执行。 183 | for 元素 in 序列: 184 |    statement 185 | else: 186 | statement 187 | ``` 188 | 189 | while 循环 190 | 191 | ```python 192 | while 条件: 193 | statement 194 | ``` 195 | 196 | while 循环使用 else 语句 197 | 198 | ```python 199 | # 如果 else 语句和 while 循环语句一起使用,则当条件变为 False 时,则执行 else 语句。 200 | while 条件: 201 |    statement 202 | else: 203 | statement 204 | ``` 205 | 206 | 中断循环:break 或 continue,与 C/C++ 功能一样。 207 | 208 | pass 语句:空语句,不做任何事情,保证程序结构完整性,防止语法错误。 209 | 210 | python 没有 do...while 循环。 211 | 212 | ## 函数 213 | 214 | ```python 215 | def 函数名(参数列表): 216 | 函数体 217 | ``` 218 | 219 | * 不可变对象:string,number,tuple 220 | * 可变对象:list,dict 221 | * 不定长参数:加了星号 `*` 的变量名会存放所有未命名的变量参数 222 | * 使用 lambda 来创建匿名函数 223 | * 默认参数必须放到最后 224 | 225 | ```python 226 | sum = lambda arg1, arg2: arg1 + arg2 227 | 228 | print(sum(10, 20)) 229 | ``` 230 | 231 | 变量的作用域: 232 | 233 | * L (Local) 局部作用域 234 | * E (Enclosing) 闭包函数外的函数中 235 | * G (Global) 全局作用域 236 | * B (Built-in) 内建作用域 237 | 238 | 以 L –> E –> G –>B 的规则查找,即:在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再者去内建中找。 239 | 240 | 当内部作用域想修改外部作用域的变量时,就要用到 global 关键字。 241 | 242 | 要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字。 243 | 244 | ```python 245 | #!/usr/bin/env python3 246 | 247 | def who(name): 248 | print(name) 249 | 250 | who(name = 'steve') 251 | ``` 252 | 253 | ## 总结 254 | 255 | 重点:函数 256 | 257 | -------------------------------------------------------------------------------- /Python 高级.md: -------------------------------------------------------------------------------- 1 | # Python 高级 2 | 3 | ## `__slots__` 4 | 5 | 创建了一个 class 的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。 6 | 7 | Python 允许在定义 class 的时候,定义一个特殊的 `__slots__` 变量,来限制该 class 实例能添加的属性。 8 | 9 | ```python 10 | class Student(object): 11 | __slots__ = ('name', 'age') # 用 tuple 定义允许绑定的属性名称 12 | ``` 13 | 14 | 注意:`__slots__` 只对当前类有效,对子类没有限制。 15 | 16 | ## @property 17 | 18 | Python 内置的 @property 装饰器是负责把一个方法变成属性调用的。 19 | 20 | ```python 21 | #!/usr/bin/env python3 22 | 23 | class Screen(object): 24 | @property 25 | def width(self): 26 | return self._width 27 | 28 | @width.setter 29 | def width(self, value): 30 | if not isinstance(value, int): 31 | raise ValueError('width must be an integer!') 32 | self._width = value 33 | 34 | @property 35 | def height(self): 36 | return self._height 37 | 38 | @height.setter 39 | def height(self, value): 40 | if not isinstance(value, int): 41 | raise ValueError('height must be an integer!') 42 | self._height = value 43 | 44 | @property 45 | def resolution(self): 46 | return self._width * self._height 47 | 48 | s = Screen() 49 | s.width = 1024 50 | s.height = 768 51 | print('resolution =', s.resolution) 52 | if s.resolution == 786432: 53 | print('测试通过!') 54 | else: 55 | print('测试失败!') 56 | ``` 57 | 58 | ## type() 动态创建类 59 | 60 | type() 既可以返回一个对象的类型,同时也可以创建新的类型。 61 | 62 | 使用 type() 动态创建类,传入三个参数: 63 | 64 | * class 的名称; 65 | * 继承的父类集合,注意 Python 支持多重继承,如果只有一个父类,别忘了 tuple 的单元素写法 66 | * class 的方法名称与函数绑定 67 | 68 | ```python 69 | #!/usr/bin/env python3 70 | # -*- coding: utf-8 -*- 71 | 72 | def fn(self, name='world'): # 先定义函数 73 | print('Hello, %s.' % name) 74 | 75 | Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class 76 | 77 | h = Hello() 78 | print('call h.hello():') 79 | h.hello() 80 | print('type(Hello) =', type(Hello)) 81 | print('type(h) =', type(h)) 82 | ``` 83 | 84 | ## Mix-In 85 | 86 | Python 支持多重继承,Mix-In 它本质上一种简化了的、受限的、简单的多重继承。 87 | 88 | Mix-In 思想在 Python 中实现方式就是多重继承,但需要注意一些使用限制避免使类的关系复杂。 89 | 90 | Mix-In 类使用需要注意的限制: 91 | 92 | 1)Mix-In 类功能需要单一,若要实现多个功能就需要创建多个 Mix-In 类 93 | 94 | 2)其次 Mix-In 类不依赖子类的实现,不能继承除了 Mix-In 以外的类 95 | 96 | 3)不单独生成使用实例(理解为一个抽象类) 97 | 98 | Mix-In 的类状图为一棵倒立的树型图。 99 | 100 | ```python 101 | class MyTCPServer(TCPServer, ForkingMixIn): 102 | pass 103 | 104 | class MyUDPServer(UDPServer, ThreadingMixIn): 105 | pass 106 | ``` 107 | 108 | ## 高阶函数 109 | 110 | 一个函数可以接收另一个函数作为参数,这种函数就称之为 高阶函数。 111 | 112 | ```python 113 | #!/usr/bin/env python3 114 | 115 | def add(x, y, f): 116 | return f(x) + f(y) 117 | 118 | print(add(-1, 3, abs)) 119 | ``` 120 | 121 | > **map/reduce** 122 | 123 | map 接收两个参数,第一个参数为函数,第二个参数是 Iterable,map 将传入的函数依次作用到序列的每个元素,并把结果作为新的 Iterator 返回。 124 | 125 | ```python 126 | #!/usr/bin/env python3 127 | 128 | def f(x): 129 | return x**2 130 | 131 | r = map(f, [1, 2, 3, 4, 5, 6]) 132 | 133 | print(list(r)) 134 | ``` 135 | 136 | reduce 接收两个参数,第一个参数为函数,第二参数是 Iterable,但是这个函数必须接收两个参数,reduce 把结果继续和序列的下一个元素做累积计算。 137 | 138 | ```python 139 | #!/usr/bin/env python3 140 | 141 | from functools import reduce 142 | 143 | def f(x, y): 144 | return x * 10 + y 145 | 146 | r = reduce(f, [1, 3, 5, 7, 9]) 147 | 148 | print(r) # 13579 149 | ``` 150 | 151 | > **filter** 152 | 153 | 作用是过滤序列,也是接收两个参数,第一个参数为函数,第二个参数是序列,filter 将函数依次作用于序列,根据 True 或 False 来过滤序列。 154 | 155 | ```python 156 | #!/usr/bin/env python3 157 | 158 | def is_odd(n): 159 | return n % 2 == 1 160 | 161 | r = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9]) 162 | 163 | print(list(r)) 164 | ``` 165 | 166 | > **sorted** 167 | 168 | 排序函数。 169 | 170 | 对字符串排序,是按照 ASCII 的大小比较的。 171 | 172 | ```python 173 | #!/usr/bin/env python3 174 | 175 | print(sorted([-5, 19, 30, -23], key=abs)) 176 | ``` 177 | 178 | ## 闭包(closure) 179 | 180 | 闭包(closure):在一个内部函数中,对外部作用域的变量进行引用,(并且一般外部函数的返回值为内部函数),那么内部函数就被认为是闭包。 181 | 182 | 函数对象作为某个函数的返回结果。 183 | 184 | 返回函数不要引用任何循环变量,或者后续会发生变化的变量。 185 | 186 | ```python 187 | #!/usr/bin/env python3 188 | 189 | def f(j): 190 | def g(): 191 | return j*j 192 | return g 193 | 194 | g1 = f(2) 195 | 196 | print(g1()) 197 | ``` 198 | 199 | 闭包作用: 200 | 201 | * 封装 202 | * 代码复用 203 | 204 | ## 装饰器(decorator) 205 | 206 | 装饰器可以对一个函数、方法或者类进行封装,更加抽象。提高了程序的可重复利用性,并增加了程序的可读性。 207 | 208 | 装饰器其实还是对闭包的一种使用,语法糖 @deco。 209 | 210 | ```python 211 | #!/usr/bin/env python3 212 | 213 | def decorator(F): 214 | def new_F(a, b): 215 | print("input", a, b) 216 | return F(a, b) 217 | return new_F 218 | 219 | # get square sum 220 | @decorator 221 | def square_sum(a, b): 222 | return a**2 + b**2 223 | 224 | # get square diff 225 | @decorator 226 | def square_diff(a, b): 227 | return a**2 - b**2 228 | 229 | print(square_sum(3, 4)) 230 | print(square_diff(3, 4)) 231 | ``` 232 | -------------------------------------------------------------------------------- /Python 进阶.md: -------------------------------------------------------------------------------- 1 | # Python 进阶 2 | 3 | ## 面向对象 4 | 5 | Python 与 Java/C++ 一样,都可以进行面向对象编程(OOP)。 6 | 7 | * class(类)、object(对象)、attribute(属性)、method(方法)、inheritance(继承)、override(重写)、多重继承、多态 8 | 9 | * 类的私有属性:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问,可以在类内部的方法中使用 10 | 11 | * 类的私有方法:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类地外部调用 12 | 13 | * 定义一个类,使用 class,在类中定义方法,参数必须有 self,通过 self 调用类的属性 14 | 15 | * 特殊方法:`__init__()`,创建对象会自动调用;类似构造函数概念 16 | 17 | * 运算符也是特殊方法,可以进行重载 18 | 19 | * 类名通常是大写开头的单词 20 | 21 | ```python 22 | class Animal(object): 23 |     name = 'Tiger' 24 |     def eat(self): 25 |         print('I can eat!', self.name) 26 | 27 | x = Animal() 28 | 29 | print(x.name) 30 | 31 | print(x.eat()) 32 | 33 | x.age = 1 # Python 允许对实例变量绑定任何数据 34 | 35 | print(x.age) 36 | ``` 37 | 38 | ## 多态 39 | 40 | ```python 41 | #!/usr/bin/env python3 42 | 43 | class Animal(object): 44 | def run(self): 45 | print('Animal is running...') 46 | 47 | class Dog(Animal): 48 | def run(self): 49 | print('Dog is running...') 50 | 51 | class Cat(Animal): 52 | def run(self): 53 | print('Cat is running...') 54 | 55 | # 不一定要继承 Animal 类型,需要 run() 方法 56 | class Xx(object): 57 | def run(self): 58 | print('Xx is running...') 59 | 60 | # 多态 61 | def run_twice(animal): 62 | animal.run() 63 | animal.run() 64 | 65 | run_twice(Animal()) 66 | 67 | run_twice(Dog()) 68 | 69 | run_twice(Cat()) 70 | 71 | run_twice(Xx()) 72 | ``` 73 | 74 | 著名的“开闭”原则: 75 | 76 | 对扩展开放:允许新增 Animal 子类; 77 | 78 | 对修改封闭:不需要修改依赖 Animal 类型的 run_twice() 等函数。 79 | 80 | 81 | ## 文件的输入和输出 82 | 83 | > **键盘输入:input()** 84 | 85 | input() 默认输入的为 str 格式。 86 | 87 | ```python 88 | #!/usr/bin/env python3 89 | 90 | str = input('Please input: ') 91 | 92 | print(str) 93 | ``` 94 | 95 | > **输出:print()** 96 | 97 | * 使用 str.format() 函数来格式化输出值 98 | * `%` 操作符也可以实现字符串格式化 99 | * 输出的值转成字符串 str() 100 | 101 | ```python 102 | #!/usr/bin/env python3 103 | 104 | name = 'steve' 105 | 106 | print('{0} 和 {1}'.format('steve', 'Lau')) 107 | 108 | print('who are you: %s' %name) 109 | ``` 110 | 111 | > **文件操作** 112 | 113 | 打开一个文件:open(filename, mode) 114 | 115 | 文件对象的方法: 116 | * 读 read() 117 | * 从文件中读取单独的一行 readline() 118 | * 读取文件中包含的所有行 readlines() 119 | * 将 string 写入到文件中, 然后返回写入的字符数 write() 120 | * 返回文件对象当前所处的位置, 它是从文件开头开始算起的字节数 tell() 121 | * 要改变文件当前的位置 seek(offset, from_what) 122 | * 关闭文件 close() 123 | 124 | 对文件的操作,还有很多方法,直接看 Python 官方文档手册 125 | 126 | ```python 127 | #!/usr/bin/env python3 128 | 129 | f = open('/home/steve/test.txt', r+) 130 | 131 | str = f.read() 132 | print(str) 133 | 134 | str = f.readline() 135 | print(str) 136 | 137 | num = f.write('Hello') 138 | print(num) 139 | 140 | off = f.seek(2) 141 | print(off) 142 | 143 | f.close() 144 | ``` 145 | 146 | ## 模块 147 | 148 | python 是胶水语言,有丰富的模块和库。 149 | 150 | 一个 .py 文件就构成一个模块。 151 | 152 | ```python 153 | # import 语句,导入模块 154 | import module1[, module2[,... moduleN] 155 | ``` 156 | ```python 157 | # from...import ... 语句,从模块中导入一个指定的部分到当前命名空间,也可以把模块的所有内容全都导入到当前的命名空间 158 | from modname import name1[, name2[, ... nameN]] 159 | 160 | from modname import * 161 | ``` 162 | 163 | 每个模块都有一个 __name__ 属性,当其值是'__main__'时,表明该模块自身在运行,否则是被引入。 164 | 165 | ```python 166 | #!/usr/bin/env python3 167 | # Filename: using_name.py 168 | 169 | if __name__ == '__main__': 170 | print('程序自身在运行') 171 | else: 172 | print('我来自另一模块') 173 | ``` 174 | 175 | 可以将功能相似的模块放在同一个文件夹中,构成一个模块包,包是一种管理 Python 模块命名空间的形式,采用"点模块名称"。 176 | 177 | 如:`import filedir.module` 178 | 179 | 该文件夹下必须包含一个 `__init__.py` 的文件,说明该文件夹是一个模块包。 180 | 181 | ## 异常处理 182 | 183 | 异常处理的格式: 184 | 185 | ```python 186 | try: 187 | ... 188 | except exception1: 189 | ... 190 | except exception2: 191 | ... 192 | except: 193 | ... 194 | else: 195 | ... 196 | finally: 197 | ... 198 | ``` 199 | 抛出指定的异常:raise 语句 200 | 201 | ```python 202 | # 定义函数 203 | def temp_convert(var): 204 | try: 205 | return int(var) 206 | except ValueError: 207 | print ('参数没有包含数字') 208 | 209 | # 调用函数 210 | temp_convert('xyz'); 211 | ``` 212 | 213 | ## 迭代器 214 | 215 | 迭代器含义与 C++ STL 迭代器一样,python 中迭代器有两种基本方法:iter() 和 next()。 216 | 217 | 字符串,列表或元组对象都可用于创建迭代器。 218 | 219 | ```python 220 | #!/usr/bin/env python3 221 | 222 | import sys 223 | 224 | list=[1, 2, 3, 4, 5] 225 | it = iter(list) # 创建迭代器对象 226 | 227 | while True: 228 |    try: 229 |        print(next(it)) # 输出迭代器的下一个元素 230 | except StopIteration: 231 | sys.exit() 232 | ``` 233 | 234 | ## generator(生成器) 235 | 236 | 使用了 yield 的函数被称为生成器(generator)。 237 | 238 | 原理:在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值。并在下一次执行 next() 方法时从当前位置继续运行。 239 | 240 | ```python 241 | #!/usr/bin/env python3 242 | 243 | import sys 244 | 245 | def fibonacci(n): # 生成器函数 - 斐波那契 246 | a, b, counter = 0, 1, 0 247 | while True: 248 | if (counter > n): 249 | return 250 | yield a 251 | a, b = b, a + b 252 | counter += 1 253 | f = fibonacci(10) # f 是一个迭代器,由生成器返回生成 254 | 255 | while True: 256 | try: 257 | print (next(f), end=" ") 258 | except StopIteration: 259 | sys.exit() 260 | ``` 261 | 1.什么时候需要使用 yield ? 262 | 263 | ## 表推导 264 | 265 | 表推导(list comprehension)是快速生成表的方法。 266 | 267 | ```python 268 | L = [x**2 for x in range(10)] 269 | 270 | print(L) 271 | ``` 272 | 273 | ## 总结 274 | 275 | > **内置函数 dir()** 276 | 277 | dir() 用来查询一个类或者对象所有属性。如 `print dir(list)` 278 | 279 | > **内置函数 help()** 280 | 281 | help() 用来查询的说明文档。 282 | 283 | > **内置函数 enumerate()** 284 | 285 | 每次循环中同时得到下标和元素。 286 | 287 | > **内置函数 zip()** 288 | 289 | 290 | --------------------------------------------------------------------------------