Python 语言基础(3.9)
Python 语言基础(3.9)
# 教材
- 视频
- 官方文档 (opens new window)
- 其他文档
- 工具
# Python 生态
Python 目前有两个主要版本 2.7, 3+,语法有所区别,Python 2 在 2020 年 1 月 1 号 停止维护 (opens new window),本文基于 Python 3.9。
- Python (opens new window):A Programming Language
- PEP (opens new window):Python Enhancement Proposals,Python 语言特性增强草案
- 包管理
- PyPI (opens new window):The Python Package Index 官方包仓库(类似 Node.js 的 npm)
- pip (opens new window)
- pipenv (opens new window):虚拟环境管理
- 包
- PyPI 榜单
- VS Code 插件
- Microsoft Python extension (opens new window):VS Code 的 Python 语言扩展
- Wolf (opens new window):类似 Quokka.js (opens new window) 的 runner
- Code Runner (opens new window):用快捷键运行当前脚本
- Tabnine (opens new window):基于 AI 的代码自动补全
- Misc
- Pythonic (opens new window):Python 风格
import this
(opens new window):REPL 里的彩蛋《The Zen of Python》
# 安装和运行(Mac)
# python, pip
brew install python@2
brew install python@3.9
python --version
python3 --version
python -m site
python3 -m site
pip --version
pip3 --version
pip install -U pip
pip install black mypy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# pipenv
pip install pipenv
pipenv --help
pipenv shell
python --version
1
2
3
4
2
3
4
# REPL, script
python
>>> import this
>>> print('hello world')
>>> exit()
python script.py
1
2
3
4
5
6
2
3
4
5
6
# Python 基础知识体系
# Python 语言特性
- 语言特性
- 动态类型,强类型
- 万物皆对象
- 函数一等公民
# 语法 语句 表达式 操作符
- 语法 (opens new window)
- 换行
- 显式拼接行
\
- 隐式拼接行
( ) [ ] { }
表达式括号内支持换行
- 显式拼接行
- 缩进
- 注释
#
,"""Multi Line"""
- 变量声明
- 有效变量名 (opens new window) 区分大小写
A-Z , a-z , 0-9 , _
- 保留字 (opens new window)
- 序列解包 (opens new window)
a, b, c = 1, 2, 3
,a = b = c = 1
- 有效变量名 (opens new window) 区分大小写
_
特殊标识符 (opens new window) 在 REPL 中获取最近一次的求值- 尾逗号 (opens new window)
- 逗号不是运算符 (opens new window) 只是分隔符
- 三目运算符 (opens new window)
small = x if x < y else y
- 换行
- 表达式 (opens new window) (运算符/操作符)
- 算数 (opens new window)
+
,-
,*
,/
,%
,//
,**
- 位运算 (opens new window)
&
,|
,^
,~
,>>
,<<
- (逻辑判断)
- 比较运算符 (opens new window)
<
,>
,==
,!=
,>=
,<=
- 可串联
- 序列的比较
- 布尔运算 (opens new window)
and
,or
,not
- 成员检测 (opens new window)
in
,not in
- identity 比较 (opens new window)
is
,is not
- set 运算 (opens new window)
<
,<=
,>
,>=
,|
,&
,-
,^
- 比较运算符 (opens new window)
- 赋值 (opens new window)
=
,+=
,*=
... - 赋值表达式/海象表达式 (opens new window)
[y for x in data if (y := f(x))]
- 运算符优先级 (opens new window)
- 算数 (opens new window)
- 序列
- 切片 (opens new window)
a[:]
,a[:-1]
,a[0:10:1]
- 索引越界
- 负数索引
- 序列的比较 (opens new window)
- 切片 (opens new window)
- del (opens new window)
- 控制流,循环 (opens new window)
if
,elif
,else
for in
,while
,else
break
,continue
pass
- with 语句 (opens new window)
- 错误和异常 (opens new window)
try
,except
,else
,finally
raise
,Exception
assert
(opens new window)
- 列表、集合、字典推导式 (opens new window)
[x for x in range(10)]
[x for x in range(10) if x % 2]
[[col + row * 3 for col in range(4)] for row in range(3)]
{x for x in range(10)}
{x: x ** 2 for x in range(10)}
# 数据类型 数据结构
- 内置类型 (opens new window),数据结构 (opens new window)
- 数字类型 (opens new window)
- int:
0b111
,0o777
,0xfff
- 无长度限制 (opens new window)
- 下划线 (opens new window) 提高可读性
1_000_000
- float:
10.5
,1.5e2
- complex:
1+2j
- int:
- str (opens new window)
'Hello'
,"Hello"
"""Multi Line"""
- 转义字符 (opens new window)
- 字符串合并 (opens new window)
- f-字符串 (opens new window)
f"x + y = {x + y}"
- .format() (opens new window)
"x + y = {}".format(1 + 2)
- .format() (opens new window)
- 原始字符串 (opens new window)
r"raw \n"
- unicode 字面值 (opens new window)
u"\u00dc \u00f6 \xf1"
- bytes (opens new window)
b'hello'
b'hello'[0] == 104
- 布尔和比较 (opens new window)
- bool:
True
,False
- 真值/假值 (opens new window)
type(1) == int
,isinstance(1, int)
id(a)
(opens new window),a is a
- bool:
None
(opens new window)- 序列类型 (opens new window)
- list:
[1, 2, 3]
- tuple (opens new window):
(1,)
,(1, 2, 3)
- 括号可以省略
- 元组打包 - 序列解包
a, b = 1, 2
- list:
- 集合 (opens new window)
- set:
{'a', 'b', 'c'}
- frozenset
- set:
- 映射/字典 (opens new window)
- dict:
{'a': 1, 'b': 2, 'c': 3}
- dict:
- 数字类型 (opens new window)
- 一些特性
- hashable (opens new window)
- immutable (opens new window) immutable 的数据都能作为 dict 的 key
- mutable (opens new window):
list
,dict
,set
- iterable (opens new window)
- 字典视图对象 (opens new window) 是动态的:
dict.keys()
,dict.values()
,dict.items()
- 隐式类型转换,显式/强制类型转换 (opens new window)
# 函数 类
- 函数 (opens new window)
- docstring (opens new window)
- 默认值参数 (opens new window)
def fn(value=2):
- 关键字参数 (opens new window)
def fn(value, *arguments, **keywords):
- 特殊参数 (opens new window)
def fn(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
- 解包实参列表 (opens new window)
fn(1, *tuple, **dict)
- Lambda 表达式 (opens new window)
add = lambda x, y: x + y
- 作用域
- Python 作用域和命名空间 (opens new window)
- 变量明明有值,为什么还会出现 UnboundLocalError? (opens new window)
- local ->
nonlocal
->global
-> built-in globals()
(opens new window),locals()
(opens new window)- 闭包
- 类 (opens new window)
- 实例/类 (opens new window)
- 实例
obj = MyClass()
- 实例化函数
def __init__(self):
- 实例变量 (opens new window)
self
- 实例
- 继承 (opens new window)
- 继承/多继承
class ClsC(ClsA, ClsB):
super()
(opens new window)
- 继承/多继承
- 私有名称 (opens new window)
__name
- 魔术方法/特殊方法 (opens new window)、运算符重载 (opens new window)
__str__
- @staticmethod (opens new window), @classmethod (opens new window)
- 实例/类 (opens new window)
# 模块化
- 模块 (opens new window), 导入系统 (opens new window)
import math
,from math import *
,from math import pi, e
import math as m
,from math import sqrt as s
import myutils.calc.add
- 相关
__name__
(opens new window),"__main__"
(opens new window)__path__
__init__.py
__all__
(opens new window)
# Python 标准库
- 内置函数 (opens new window)
print
,input
int
,float
,complex
,bool
dict
,set
,frozenset
str
,tuple
,list
,iter
,len
,range
,sorted
dir
,locals
,globals
hash
,id
,isinstance
,issubclass
abs
,round
,max
,min
,pow
,sum
map
,filter
- 内置库 (opens new window)
- 数学
- array (opens new window):数组
- datetime (opens new window):时间和日期
- re (opens new window):正则表达式
- json (opens new window):(注意到 Python 的 dict 和 JS 的 object 不一样)
# 类型提示
a: list[int] = [1, 2]
# Incompatible types in assignment (expression has type "float", variable has type "List[int]") mypy(error)
a = 2.3
1
2
3
4
2
3
4
def greeting(name: str) -> str:
return "Hello " + name
# Argument 1 to "greeting" has incompatible type "int"; expected "str" mypy(error)
greeting(233)
1
2
3
4
5
2
3
4
5
# 高级使用
- iterator (opens new window)
__iter__
,__next__
- generator (opens new window)
yield
- decorator (opens new window)
@f
- 描述器(getter/setter)
- 协程与任务 (opens new window)
# Python 代码
# nonlocal 1
def calc(x=0):
def add():
nonlocal x
x += 1
print("inner", x)
def minus():
nonlocal x
x -= 1
print("inner", x)
return add, minus
add, minus = calc()
add()
add()
add()
minus()
minus()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# nonlocal 2
def a():
x = 1
def b():
def c():
nonlocal x
x += 1
print("c", x)
print("b1", x)
c()
print("b2", x)
print("a1", x)
b()
print("a2", x)
a()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 类实例属性查找
class Student:
name = "noname"
def __init__(self, name):
print("default_name:", self.name)
self.name = name
print("init_name:", self.name)
def get_name(self):
print("method_log:", self.name)
lc = Student("LC")
print("\nout log:", lc.name)
lc.get_name()
del lc.name
print("\nout log:", lc.name)
lc.get_name()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
上次更新: Jan 29, 2022 6:01 PM