编辑
2023-08-01
编程
00

目录

1. 安装那些事
环境变量
pip
管理
指定源下载
1 清华大学(完全度和速度都很好,是一个优秀的pip镜像源)
2 阿里云(完全度和速度也很好,是一个不错的选择)
3 网易(速度比较快,但是完全度有限)
4 豆瓣(速度较快,但是完全度也有限)
5 百度云(速度较快,但是完全度也有限)
6 中科大(速度较快,但完全度不如前面几个镜像源)
7 华为云(完全度和速度均中等)
8 腾讯云(速度一般,完全度也一般)
2. 基础语法
2.1 注释
2.2 变量
变量类型
声明
查看类型
命名规范
类型转换
2.3 运算符
2.3.1 算数运算符
2.3.2 赋值运算符
2.3.3 符合赋值运算符
2.3.4 比较运算符
2.3.5 逻辑运算符
2.4 输入输出
2.4.1 输出
2.4.2 输入
2.4 流程控制/循环语句
2.4.1 判断
2.4.2 for循环
2.4.3 range
2.4.4 while 循环
2.4.5 跳出循环
break
continue
2.5 数据类型详细
2.5.1 字符串
2.5.2 列表
2.5.3 元组
2.5.4 切片
2.5.5 字典
遍历
2.5.6 集合
2.6 函数
2.6.1 函数的定义
2.6.2 参数与重载问题
调用失败
调用行上方的方法为准
python变长
python 默认参数
python 指定参数
Python 参数解包
2.6.3 文档字符串
2.6.4 作用域
2.6.5 高阶函数
函数式编程
闭包
装饰器
2.7 面向对象
2.8 模块化( module )
2.8.1 基础
2.8.2 包
3. 高级
3.1 Python 标准库
3.2 异常
3.3 文件操作

AI 作为时代的主旋律,了解和学习是必须得

  • Python是AI的主要编程语言:Python是开发和实施AI算法的首选语言之一。许多重要的AI库和框架,如TensorFlow、PyTorch、scikit-learn等,都是用Python编写的。

  • 丰富的AI库和工具:Python生态系统中有许多用于机器学习、深度学习、自然语言处理(NLP)等领域的优秀库和工具。这些库使你能够快速开发、训练和测试AI模型。

  • 可移植性和跨平台性:Python是跨平台的编程语言,可以在不同操作系统上运行。这使得你可以在不同的环境中部署和运行AI应用程序。

1. 安装那些事

环境变量

#python

I:\Environment\python\

#pip

I:\Environment\python\Scripts\

pip

关于包管理还会用到 python虚拟环境、conda 等不同计算。比如 llama2,通义千问 等ai模型,都用了 conda 作为包管理, 而创建不同的python虚拟环境也可以把不同项目的依赖隔离开。

管理

  • 安装包: 最好安装在 Scripts 目录下

pip install <包名>

cmd
C:\Users\haogg>I: I:\>cd I:\Environment\python\Scripts\ I:\Environment\python\Scripts>pip install ipython Collecting ipython Downloading ipython-8.14.0-py3-none-any.whl (798 kB) ... Installing collected packages: wcwidth, pure-eval, pickleshare, executing, backcall, traitlets, six, pygments, prompt-toolkit, parso, decorator, colorama, matplotlib-inline, jedi, asttokens, stack-data, ipython Successfully installed asttokens-2.2.1 backcall-0.2.0 colorama-0.4.6 decorator-5.1.1 executing-1.2.0 ipython-8.14.0 jedi-0.19.0 matplotlib-inline-0.1.6 parso-0.8.3 pickleshare-0.7.5 prompt-toolkit-3.0.39 pure-eval-0.2.2 pygments-2.16.1 six-1.16.0 stack-data-0.6.2 traitlets-5.9.0 wcwidth-0.2.6 [notice] A new release of pip is available: 23.1.2 -> 23.2.1 [notice] To update, run: python.exe -m pip install --upgrade pip
  • 删除包

pip uninstall <包名>

  • 显示已安装包

pip list

pip freeze

指定源下载

shell
pip install <包名> -i <国内地址>
1 清华大学(完全度和速度都很好,是一个优秀的pip镜像源)
text
https://pypi.tuna.tsinghua.edu.cn/simple
2 阿里云(完全度和速度也很好,是一个不错的选择)
text
https://mirrors.aliyun.com/pypi/simple/
3 网易(速度比较快,但是完全度有限)
text
https://mirrors.163.com/pypi/simple/
4 豆瓣(速度较快,但是完全度也有限)
text
https://pypi.douban.com/simple/
5 百度云(速度较快,但是完全度也有限)
text
https://mirror.baidu.com/pypi/simple/
6 中科大(速度较快,但完全度不如前面几个镜像源)
text
https://pypi.mirrors.ustc.edu.cn/simple/
7 华为云(完全度和速度均中等)
text
https://mirrors.huaweicloud.com/repository/pypi/simple/
8 腾讯云(速度一般,完全度也一般)
text
https://mirrors.cloud.tencent.com/pypi/simple/

2. 基础语法

2.1 注释

单行注释以 # 号开头 多行注释用 ''' 前后包裹

python
# 单行注释以 # 号开头 ''' 这是多行注释 '''

2.2 变量

格式: 变量名 = 变量值

python
variable = '这是变量' print(variable)

变量类型

  • numbers 数字
    • int 有符号整型
    • float 浮点型
    • complex 复数
  • bool 布尔型
    • True
    • False
  • String 字符串
  • List 列表
  • Tuple 元组
  • Dictionary 字典
  • Set 集合

声明

python
# number # int number1 = 1 # float number2 = 1.1 # 复数 1 + 3j number3 = complex(1, 3) # boolean bool1 = True bool2 = False # String String1 = "string variable" String2 = 'tes\'t\'' print(String2) # list list1 = [1, 2, 3] # Tuple 元组 tuple1 = (1, 2, 3, 4) # Dictionary 字典 dict1 = {'name': 'test1', 'age': '11'} print(dict1) # Set 集合 s = {1, 2, 3, 4} print(type(s))

查看类型

type(<变量>)

python
# type() 查看变量类型 type1 = type(dict1) print(type1) print(type1 == type({})) ''' 输出: <class 'dict'> True '''

命名规范

  • 严格区分大小写
  • 不能数字开头
  • 字母 数字 下划线
  • 不能关键字

命名规范和格式规范可以参考 pep8

类型转换

函数说明
int(x)将x转换为一个整型
float(x)将x转换为一个浮点型
str(x)将x转换为一个字符串
bool(x)将x转换为一个布尔值

2.3 运算符

2.3.1 算数运算符

python符号描述java符号
++
--
**
//
//取整- (类型转换)
%取余%
**指数Math.pow(a, b)
()小括号()

2.3.2 赋值运算符

python
# 等号赋值 a = 10 # 多个变量共同赋值 b = c = 20 # 多个变量分别赋值 d, e, f = 1, 'string', 1.1

2.3.3 符合赋值运算符

运算同时赋值

a += b

等价于:

a = a + b

运算符描述
+=加法赋值运算符
-=减法赋值运算符
*=乘法赋值运算符
/=除法赋值运算符
//=取整赋值运算符
%=取模赋值运算符
**=幂赋值运算符

2.3.4 比较运算符

运算符描述
==等于
!=不等于
>大于
>=大于等于
<小于
<=小于等于

2.3.5 逻辑运算符

运算符表达式描述java表达式
andx and y与,只要有一个是 False 就为 Falsex & y
orx or y或,只要有一个是 True 就为 Truex | y
notnot x非,取反,如果为 True 则为 False!x

特殊用法:

shell
a < 10 and pring(’hello world‘)

2.4 输入输出

2.4.1 输出

  • print

  • 格式化输出: print('xxx %d %s' % (1, 'a'))

    • %s 代表字符串
    • %d 代表数字

2.4.2 输入

input('提示:')

python
i = input('输入:') i2 = input('输入:') print("类型:%s ,类型2:%s" % (type(i), type(i2))) # 输出 ==== 输入:1 输入:aaa 类型:<class 'str'> ,类型2:<class 'str'>

2.4 流程控制/循环语句

2.4.1 判断

python
# 1. if if ${expression} : code # 2. if .. else if ${expression} : code1 else: code2 # 3. if elif if ${expression} : code1 elif ${expression2} : code2 else: code3

例如:

python
age = int(input("你的年龄")) if age >= 18: print("青少年") else: print("不是青少年") if age >= 18: print("我成年了") elif age <= 30: print("我是青少年") else: print("我不是青少年")

2.4.2 for循环

python
for 临时变量 in 列表: code1

例如:

python
for i in '我是谁?': print(i) #=======输出 我 是 谁 ?

2.4.3 range

python
# 生成一个[起始值, 结束值) range(起始值, 结束值, 步长)

例如:

python
print(type(range(1, 11,5))) for i in range(1, 11, 1): print(i) #=======输出 <class 'range'> 1 2 3 4 5 6 7 8 9 10

2.4.4 while 循环

python
cnt = int(input("打印次数:")) while cnt > 0: cnt -= 1 print("打印!") # =====================输出 打印次数:2 打印! 打印!

2.4.5 跳出循环

break

立刻跳出循环

continue

跳过当次循环

2.5 数据类型详细

2.5.1 字符串

  • len 获取字符串长度
  • find 获取字符串第一次的长度,不存在
  • startswith 是否以什么开头, endswith 是否以什么结尾
  • count 计算出现的次数
  • split 切割字符串
  • upper lower 大小写互换
  • strip 去除开头和结尾空格,或者指定字符
  • join 字符串拼接
python
s = 'China' # len 获取字符串长度 print('len 获取字符串长度: %d' % len(s)) # find 获取字符串第一次的长度,不存在 print('find 存在时:%d' % s.find('i')) print('find 不存在时:%d' % s.find('w')) # startswith 是否以什么开头, endswith 是否以什么结尾 print('startswith 存在时:%s' % s.startswith('Chi')) print('startswith 从指定位置开始:%s' % s.startswith('ina', 2)) print('startswith 从指定位置开始指定位置结束:%s' % s.startswith('hina', 1, 4)) print('startswith 从指定位置开始指定位置结束:%s' % s.startswith('hina', 1, 5)) # count 计算出现的次数 s2 = 'chinese' print('count 计算出现的次数: %d' % s2.count('i')) print('count 计算出现的次数: %d' % s2.count('e')) # replace 替换字符串 # replace(原字符串, 新字符串, 替换次数) print('replace 替换字符串: %s' % s2.replace('e', 'w', 1)) print('replace 替换字符串: %s' % s2.replace('e', 'w')) # split 切割字符串 s3 = "1,2,3,4,5,6,7" print('split 切割字符串:%s' % type(s3.split(','))) print('split 切割字符串:%s' % s3.split(',')) print('split 切割字符串:%s' % s3.split(',', 2)) # upper lower 大小写互换 print(s) print('upper lower 大小写互换: %s' % s.upper()) print('upper lower 大小写互换: %s' % s.lower()) # strip 去除开头和结尾空格,或者指定字符 s4 = ' i am Chinese, ha ha haaaa' print("strip 去除开头和结尾空格,或者指定字符: %s" % s4.strip()) print("strip 去除开头和结尾空格,或者指定字符: %s" % s4.strip('a')) # join 字符串拼接 print('join 字符串拼接: %s' % s3) print('join 字符串拼接: %s' % 'a'.join(s3)) print('join 字符串拼接: %s' % 'ab'.join(s3)) #==============输出 len 获取字符串长度: 5 find 存在时:2 find 不存在时:-1 startswith 存在时:True startswith 从指定位置开始:True startswith 从指定位置开始指定位置结束:False startswith 从指定位置开始指定位置结束:True count 计算出现的次数: 1 count 计算出现的次数: 2 replace 替换字符串: chinwse replace 替换字符串: chinwsw split 切割字符串:<class 'list'> split 切割字符串:['1', '2', '3', '4', '5', '6', '7'] split 切割字符串:['1', '2', '3,4,5,6,7'] China upper lower 大小写互换: CHINA upper lower 大小写互换: china strip 去除开头和结尾空格,或者指定字符: i am Chinese, ha ha haaaa strip 去除开头和结尾空格,或者指定字符: i am Chinese, ha ha h join 字符串拼接: 1,2,3,4,5,6,7 join 字符串拼接: 1a,a2a,a3a,a4a,a5a,a6a,a7 join 字符串拼接: 1ab,ab2ab,ab3ab,ab4ab,ab5ab,ab6ab,ab7

2.5.2 列表

  • append 在末尾添加元素
  • insert 在指定位置插入元素
  • extend 合并两个列表
python
list1 = [1, 2, 3, '4'] print(list1) print(type(list1)) # 不同元素类型可以不一样 for temp in list1: print("list的元素类型: %s" % type(temp)) # append 尾部拼接 list1.append('5') print(list1) # 指定位置插入 list1.insert(0, '0') print(list1) list1.insert(1, 'a') print(list1) # extend 拼接 list2 = ['a', 'b', 'c'] list3 = [1, 2, 3] list2.extend(list3) print(list2) #==============输出 [1, 2, 3, '4'] <class 'list'> list的元素类型: <class 'int'> list的元素类型: <class 'int'> list的元素类型: <class 'int'> list的元素类型: <class 'str'> [1, 2, 3, '4', '5'] ['0', 1, 2, 3, '4', '5'] ['0', 'a', 1, 2, 3, '4', '5'] ['a', 'b', 'c', 1, 2, 3]
python
list4 = [1, 2, 3, 4] list4[1] = 1 print(list4) #==============输出 [1, 1, 3, 4]
python
list5 = ['a', 'b', 'c', 1, '2'] print('in 测试查找: %s' % (2 in list5)) print('in 测试查找: %s' % ('2' in list5)) print('not in 测试查找: %s' % (2 not in list5)) print('not in 测试查找: %s' % ('2' not in list5)) #==============输出 in 测试查找: False in 测试查找: True not in 测试查找: True not in 测试查找: False
  • del 根据下标删除
  • pop 删除最后一个元素(或指定下标元素),并返回该元素
  • remove 根据元素的值进行删除,只删除第一个
python
list6 = [1, 2, 3, 4, 5, 6, 8, 9, 8, 9, 8] del list6[1] print('del 根据下标删除元素测试:%s' % list6) print('pop 删除最后一个元素并返回: %s' % list6.pop()) print('pop 删除最后一个元素并返回后: %s' % list6) print('pop index 删除指定元素并返回: %s' % list6.pop(2)) print('pop 删除指定元素并返回后: %s' % list6) print('remove 删除指定元素值:%s' % list6.remove(8)) print('remove 删除指定元素值后:%s' % list6) # ===========输出 del 根据下标删除元素测试:[1, 3, 4, 5, 6, 8, 9, 8, 9, 8] pop 删除最后一个元素并返回: 8 pop 删除最后一个元素并返回后: [1, 3, 4, 5, 6, 8, 9, 8, 9] pop index 删除指定元素并返回: 4 pop 删除指定元素并返回后: [1, 3, 5, 6, 8, 9, 8, 9] remove 删除指定元素值:None remove 删除指定元素值后:[1, 3, 5, 6, 9, 8, 9]

2.5.3 元组

元组与列表类似,不同之处在于

  • 元组的元素不能修改
  • 元组使用小括号,列表使用方括号
  • 定义只有一个元素的元组时,在元素后面必须加一个逗号,否则不是元组类型
python
tuple1 = (1,) tuple2 = (1) print("类型1: %s, 类型2: %s" % (type(tuple1), type(tuple2))) #============输出 类型1: <class 'tuple'>, 类型2: <class 'int'>

2.5.4 切片

切片指截取对象一部分的操作,字符串、列表、元组 都支持切片操作

语法:

[起始 : 结束 : 步长]

  • 起始:代表起始坐标,从0开始算
    • 如果起始大于 len ,输出空数组
    • 如果起始为负数 -n,则从 len() + (-n) 为起点
  • 结束:代表结束坐标,不包括在其中
    • 如果大于 len ,则认为 len
    • 如果为负数 -n,则认为输出到 len() + (-n) 为起点
  • 步长:下一个下标为 当前坐标 + 步长
    • 如果大于len, 则输出起始点
    • 如果为负数-n, 则认为逆向输出,步长为n
shell
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print('只有起始:%s' % list1[1:]) print('只有起始和结尾:%s' % list1[1:8]) print('只有起始和步长:%s' % list1[1::2]) print('全:%s' % list1[1:8:2]) print('只有结束:%s' % list1[:8]) print('只有结束和步长:%s' % list1[:8:2]) print('只有步长:%s' % list1[::2]) print('只有起始超过下标:%s' % list1[len(list1)::]) print('只有结束超过下标:%s' % list1[:len(list1):]) print('只有步长超过下标:%s' % list1[::len(list1)]) print('起始为负数:%s' % list1[-2::]) print('起始为负数:%s' % list1[len(list1) - 2::]) print('结束为负数:%s' % list1[:-2:]) print('结束为负数:%s' % list1[:len(list1)-2:]) print('步长为负数:%s' % list1[::-1]) print('类型:%s' % type(list1[::])) print('类型:%s' % type(list1[1:2:1])) tuple2 = (1, 2, 3) print('类型:%s' % type(tuple2[1:2:1])) # =================== 输出 只有起始:[2, 3, 4, 5, 6, 7, 8, 9, 10] 只有起始和结尾:[2, 3, 4, 5, 6, 7, 8] 只有起始和步长:[2, 4, 6, 8, 10] 全:[2, 4, 6, 8] 只有结束:[1, 2, 3, 4, 5, 6, 7, 8] 只有结束和步长:[1, 3, 5, 7] 只有步长:[1, 3, 5, 7, 9] 只有起始超过下标:[] 只有结束超过下标:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 只有步长超过下标:[1] 起始为负数:[9, 10] 起始为负数:[9, 10] 结束为负数:[1, 2, 3, 4, 5, 6, 7, 8] 结束为负数:[1, 2, 3, 4, 5, 6, 7, 8] 步长为负数:[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 类型:<class 'list'> 类型:<class 'list'> 类型:<class 'tuple'>

2.5.5 字典

get (key, [default value])

xxx[key]

get 获取不到返回 None

[] 获取不到,抛出异常

xxx['key'] = new value

xxx['new key'] = value

del xxx[key]

del xxx

clear()

del 删除指定 key,clear 清空所有 key, del 不指定 key 把整个对象都删除了

python
dict1 = {'age': 14, 'name': 'yui'} # 查看 print('下标查看元素:%s' % dict1['age']) print('get 查看元素: %s' % dict1.get('age')) print('get 不设置默认值:%s' % dict1.get('sex')) print('get 设置默认值:%s' % dict1.get('sex', '男')) # 修改 dict1['age'] = 19 print('修改后: %s' % dict1) # 新增 dict1['sex'] = '男' print('新增后: %s' % dict1) # 删除 del dict1['sex'] print('del 删除后: %s' % dict1) dict1.clear() print('clear 删除后: %s' % dict1) del dict1 print('del 删除整个后: %s' % type(dict1)) # ==================== 输出 Traceback (most recent call last): File "F:\Study\CodePython\base\1\simple.py", line 225, in <module> print('del 删除整个后: %s' % type(dict1)) ^^^^^ NameError: name 'dict1' is not defined. Did you mean: 'dict'? 下标查看元素:14 get 查看元素: 14 get 不设置默认值:None get 设置默认值:男 修改后: {'age': 19, 'name': 'yui'} 新增后: {'age': 19, 'name': 'yui', 'sex': '男'} del 删除后: {'age': 19, 'name': 'yui'} clear 删除后: {}
遍历
python
dict2 = {'age': 14, 'name': 'yui'} for key in dict2.keys(): print('key: %s' % key) for value in dict2.values(): print('value: %s' % value) for key, value in dict2.items(): print('key: %s, value: %s' % (key, value)) for items in dict2.items(): print(type(items)) print(items) # ============== 输出 key: age key: name value: 14 value: yui key: age, value: 14 key: name, value: yui <class 'tuple'> ('age', 14) <class 'tuple'> ('name', 'yui')

2.5.6 集合

python
set1 = {value1, value2。。。} set2 = set()
  • set 的元素必须是不可变的
  • 空集合需要通过 set() 定义
  • set 元素不可以重复
  • 可以通过 set() 将 list, dict 转换为集合
  • set() 转换字典时,只包含字典的 key
  • set 是无序的

集合运算

python
交集 set1 & set2 并集 set1 | set2 差集 set1 - set2 异或 set1 ^ set2 检查一个集合是否是一个集合的子集 set1 <= set2 检查一个集合是否是一个集合的真子集 set1 < set2 检查一个集合是否是一个集合的超集 set1 >= set2 检查一个集合是否是一个集合的真超集 set1 > set2

2.6 函数

2.6.1 函数的定义

python
def function_name([...args]): code return <result>

2.6.2 参数与重载问题

  • Python 不支持传统的重载方式, 以最靠近调用行上方的方法为准
  • Python 通过参数默认值和可变参数来模拟方法重载的方式
    • 形参前面加个*号,如 *args 为元组
    • 形参前面加两个*号, 如 **args 为字典,可以用关键字指定参数
    • 入参也可以反过来通过实参前面加 星号,来进行参数的解包
  • Python 可以返回多个结果,结果使用 元组 方式返回
  • Python 可以通过关键字参数指定参数
  • Python 不会检查实参的类型,
调用失败
python
def my_sum(v1, v2): return v1 + v2 def my_sum(v1, v2, v3): return sum(sum(v1, v2), v3) r1 = my_sum(1, 2) print(r1) #======================输出 Traceback (most recent call last): File "F:\Study\CodePython\base\1\simple.py", line 252, in <module> r1 = my_sum(1, 2) ^^^^^^^^^^^^ TypeError: my_sum() missing 1 required positional argument: 'v3'
调用行上方的方法为准
python
def my_sum(v1, v2): return v1 + v2 print(my_sum(1, 2)) def my_sum(v1, v2, v3): return v1 + v2 +v3 print(my_sum(1, 2, 3)) # =====================输出 3 6
python变长
python
def my_sum(*args): print(type(args)) result = 0 for temp in args: result += temp return result print(my_sum(1, 2, 3)) print(my_sum(1, 2, 3, 4)) # =====================输出 <class 'tuple'> 6 <class 'tuple'> 10
python 默认参数
python
def my_sum(v1, v2=1): return v1 + v2 print(my_sum(1)) print(my_sum(1, 2)) # =====================输出 2 3

python 多个返回

python
def double_result(): return 1, 'b' r1, r2 = double_result() print("r1: %s, r2: %s" % (r1, r2)) print(double_result()) print(type(double_result())) # =====================输出 r1: 1, r2: b (1, 'b') <class 'tuple'>
python 指定参数
python
def display(class_name, student_name, teacher_name): print("class name: %s, student name: %s, teacher name: %s" % (class_name, student_name, teacher_name)) display('测试1', '名字1', 't2') display('t2', teacher_name='测试2', student_name='名字2') # ===================输出 class name: 测试1, student name: 名字1, teacher name: t2 class name: t2, student name: 名字2, teacher name: 测试2
Python 参数解包
  • 元组解包 *tuple
  • 字典解包 **dict , 变为关键字参数
python
def display(a, b, c): print("a: %s, b: %s, c: %s" % (a, b, c)) tuple1 = (1, 2, 3) display(*tuple1) tuple2 = (1, 2, 3, 4, 5) display(*tuple2[1:4:1]) #===================输出 a: 1, b: 2, c: 3 a: 2, b: 3, c: 4

2.6.3 文档字符串

  • 获取函数使用说明
python
help(function)
  • 自定义函数说明(doc str)
python
def function(): ''' 文档说明 ''' return
  • 参数和返回说明: 冒号 + 类型 参数说明, -> + 类型 结果说明,提示作用,不起限制
python
def fn(args<:type>) -> int: code

2.6.4 作用域

python
global 变量 = 变量值
  • 通过 global 可以使变量变成全局
  • 其他的与 java 类似

命名空间

本质是一个字典,专门用来存储变量的

通过:

python
locals()
  • 获取当前作用域的命名空间
python
def display(a, b, c): # print("a: %s, b: %s, c: %s" % (a, b, c)) print('local:%s' % locals()) print(locals()) display(1, 2, 3) # =================输出 {'__name__': '__main__', '__doc__': '\n多行注释\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001195C185150>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'F:\\Study\\CodePython\\base\\1\\simple.py', '__cached__': None, 'display': <function display at 0x000001195C1304A0>} local:{'a': 1, 'b': 2, 'c': 3}

2.6.5 高阶函数

函数式编程
  • 函数可以作为参数传入使用
  • 匿名函数 lambda 参数列表 : 返回值
python
def fn(lst, fnc): new_list = [] for n in lst: if fnc(n): new_list.append(n) return new_list def over5(n): return n > 5 l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(fn(l, over5)) print(fn(l, lambda n: n % 2 == 0)) #=====================输出 [6, 7, 8, 9, 10] [2, 4, 6, 8, 10]
python
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list(filter(lambda i: i % 2 == 0, l))) l.sort(key=lambda t: -t) print(l) #=====================输出 [2, 4, 6, 8, 10] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
闭包

将函数作为返回值返回

python
def fn(add): a = add def inner(): print('a : %d' % a) return inner r1 = fn(10) r2 = fn(11) r1() r2() #================== 输出 a : 10 a : 11
装饰器
  • 通过函数入参构造新函数
  • 通过 @funname 为函数添加装饰器
  • @装饰器 可以同时添加多个装饰器, 越靠近函数的 @装饰器 越先装饰
python
def add(a, b): return a + b def mul(a, b): return a * b def begin_end(func, *args, **kwargs): def new_funtion(*in_args, **in_kwargs): print('入参为:%s' % (list(in_args) + list(in_kwargs))) result = func(*in_args, **in_kwargs) print('结果为: %s' % result) return result return new_funtion(*args, **kwargs) def begin_end2(func): def new_funtion(*in_args, **in_kwargs): print('入参为:%s' % (list(in_args) + list(in_kwargs))) result = func(*in_args, **in_kwargs) print('结果为: %s' % result) return result return new_funtion begin_end(add, 1, 2) begin_end(mul, 2, 2) begin_end2(add)(3, 4) fun = begin_end2(mul) fun(3, 3) @begin_end2 def div(a, b): return a / b div(10, 2) #=====================输出 入参为:[1, 2] 结果为: 3 入参为:[2, 2] 结果为: 4 入参为:[3, 4] 结果为: 7 入参为:[3, 3] 结果为: 9 入参为:[10, 2] 结果为: 5.0

2.7 面向对象

python
class 类名[(父类)]: code
  • 创建对象
python
对象变量 = 类名()
  • 检查对象是否是类的实例
python
isinstance(object, class)
  • 类 是一个 type 类型的对象
python
type(MyClass) # <class 'type'>
  • 方法参数一定需要有形参 self, 它是对类的当前实例的引用

  • 初始化方法

python
def __init__(self[, args……]): code
  • 使用算下划线开头 __ 命名的变量只能在类内部访问

    • 本质上是编译器把 __name 改为 _className__name
  • @property 修饰的方法可以直接当成属性调用, 一般用在 getter 上

    • 方法和属性同名,可以屏蔽属性的直接调用,转为调用方法
    • setter 方法用: @属性名.setter
    • 但是这种方法也是需要对内使用不同变量名
  • 继承:class ClassName(SupperName……)

    • 如果没有声明父类,默认为 object
    • issubclass : 检查一个类是否是另一个类的子类
    • isinstance: 检查一个对象是否是一个类的实例
    • 重写方法,以最近为原则:
      • 当前类有则使用当前类
      • 如果没有则去父类查找
      • 如果多个父类,则按从左到右查找(每个都会先找自己,再找父类,没有才会下一个)
    • super() 调用父类
    • 类名.__bases__ 获取当前类所有父类
  • 特殊方法:

    • __del__() 方法,会在对象被回收时调用
    • __str__() -> toString()
    • __repr__ 使用 repr函数时生效,指定对象再交互模式中输出的结果
    • __lt__() : < , 重写后使用 < 号生效,入参 other 表示和当前对象比较的对象
    • __le__() : <=
    • __eq__() : ==
    • __ne__() : !=
    • __gt__() : >
    • __ge__() : >=
    • __bool__() : 转换成 boolean 类型是调用,返回结果则为转换结果
    • 官方文档: special-method-names
python
class Person: # 通过 Person.count 访问,为静态变量 # 通过 Object.count 访问,如果对象本身存在该变量,则返回本身变量,否则返回 Person.count # 公共属性 count = 0 # 初始化方法 def __init__(self, name, age) -> None: """ 构造函数 :param name: 名字 :param age: 年龄 """ super().__init__() self.__name = name self.__age = age Person.count += 1 def intro(self) -> None: print("我是: %s, 今年 %d 岁" % (self.__name, self.age)) @property def age(self): # 这里 __age 改成 age 会变成循环调用,报错 return self.__age @age.setter def age(self, age): self.__age = age print(type(Person)) print(type(type)) xiaomin = Person('小明', 11) xiaomin.count = 10 xiaohong = Person('小红', 11) print(xiaomin.count) print(xiaohong.count) print(Person.count) print("隐藏的实质 %s" % xiaomin._Person__name) print("@property %s" % xiaomin.age) xiaomin.age = 13 print("@property %s" % xiaomin.age) # ================== 输出 <class 'type'> <class 'type'> 10 2 2 隐藏的实质 小明 @property 11 @property 13

继承

python
# 继承 class Phone: def __init__(self): self.__weight = None def __int__(self, weight): self.__weight = weight @property def weight(self) -> int: return self.__weight @weight.setter def weight(self, weight) -> None: self.__weight = weight def run(self): print('phone: %s' % self.weight) class XiaoMi(Phone): # 重写 run def run(self): print('XiaoMi: %s' % self.weight) class IPhone(Phone): def run(self): print('IPhone: %s' % self.weight) class IMi(IPhone, XiaoMi): pass class MiI(XiaoMi, IPhone): pass phone1 = IMi() phone2 = MiI() phone1.weight = 10 phone2.weight = 11 phone1.run() phone2.run() print('获取所有父类:%s' % list(type(phone1).__bases__)) # ======================= 输出 IPhone: 10 XiaoMi: 11 获取所有父类:[<class '__main__.IPhone'>, <class '__main__.XiaoMi'>]

2.8 模块化( module )

2.8.1 基础

  • 创建模块: 一个 .py 文件就是一个模块
  • 引入模块:(不用在意路径)
python
# 这种方式需要通过 模块名|别名.filed 使用模块属性 import 模块名(文件名,不包含.py) [as 别名] # 只引入部分代码 from 模块名 import 方法名|类名, ... as 别名,... # 也是引入全部内容, 不建议使用,相当于代码都引入,容易被当前模块覆盖 from 模块名 import *
  • 同一个模块引入多次,模块实例只会被运行一次

  • __name__ 获取当前模块名字

    • 如果是执行的文件(主模块),则模块名为 __main__
  • 添加了下划线的变量,只能在模块内部被使用

2.8.2 包

  • 普通模块是个 .py 文件, 包是一个文件夹
  • 包的文件中必须要有 __init__.py 文件

3. 高级

3.1 Python 标准库

官方文档

module index

  • sys
    • sys.argv python运行时的参数列表
    • sys.modules 当前程序中引入的所有模块
    • sys.path 模块搜索路径列表
    • sys.platform 运行代码的平台
    • sys.exit() 退出当前程序
  • pprint
    • pprint.pprint() 对打印数据进行格式化
  • os 对系统进行访问
    • os.environ() 获取系统的环境变量
    • os.system() 获取执行操作系统的命令

3.2 异常

官方文档

  • 格式
python
# 异常的捕获 try: code1(可能出现错误代码) except [异常类型, Exception 全部异常] [as 实例名]: code2(异常时处理代码) else: code3(没出错时要执行的代码) finally: code4(无论如何都会执行)
  • 自定义异常
python
# 抛出异常 raise Exception("异常了") # 自定义异常: 类继承 Exception class MyError(Exception): code

3.3 文件操作

open

python
# with... as... 自动资源管理 with open(file_name) as file_obj: pass
  • read
python
file_name = 'simple2.py' try: with open(file_name, encoding='utf-8') as file: chunk = 100 content = '' while True: temp = file.read(chunk) if not temp: break content += temp print(content) except FileNotFoundError: print(f'{file_name} 不存在')
  • readline() 读取一行
  • readlines() 读取所有行
  • 文件模式
    • r 只读
    • w 如果文件不存在则会创建,如果存在则覆盖
    • a 追加写入
    • + 修改权限
      • r+ 可读可写,文件不存在会报错
      • w+
      • a+
    • rb 读取二进制文件
python
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True) ''' 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) '''
  • file.tell() 读取到当前文件的位置
  • file.seek(offset, whence) 切换读取位置,
    • 参数1为切换到的位置
    • 参数2为计算位置方式
      • 0: 从头计算,默认值
      • 1: 从当前位置计算
      • 2: 从最后位置开始计算

本文作者:Yui_HTT

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!