前端指南 前端指南
指南
资源
  • 刷力扣 (opens new window)
  • 手写题 (opens new window)
  • 归档
  • 分类
  • 标签
  • 关于我
  • 关于本站
GitHub (opens new window)

Seognil LC

略懂点前端
指南
资源
  • 刷力扣 (opens new window)
  • 手写题 (opens new window)
  • 归档
  • 分类
  • 标签
  • 关于我
  • 关于本站
GitHub (opens new window)
  • Python 语言基础(3.9)

    • 教材
      • Python 生态
        • 安装和运行(Mac)
          • python, pip
          • pipenv
          • REPL, script
        • Python 基础知识体系
          • Python 语言特性
          • 语法 语句 表达式 操作符
          • 数据类型 数据结构
          • 函数 类
          • 模块化
          • Python 标准库
          • 类型提示
          • 高级使用
        • Python 代码
          • nonlocal 1
          • nonlocal 2
          • 类实例属性查找
      • note
      • programming-language
      Seognil LC
      2021-08-01
      目录

      Python 语言基础(3.9)

      Python 语言基础(3.9)

      # 教材

      • 视频
        • Learn Python Programming - Python Course (opens new window) 2h
        • Python Tutorial - Python for Beginners [Full Course] (opens new window) 4h + 2h demo
      • 官方文档 (opens new window)
        • Python 教程 (opens new window)
        • Python 语言参考手册 (opens new window)
        • Python 标准库 (opens new window)
          • 内置函数 (opens new window)
          • 内置类型 (opens new window)
        • 术语对照表 (opens new window)
        • 编程常见问题 (opens new window)
        • 设计和历史常见问题 (opens new window)
      • 其他文档
        • Python Quizzes – Real Python (opens new window)
        • Learn Python in Y Minutes (opens new window)
        • Learn Python Programming (opens new window)
        • python3-in-one-pic (opens new window)
      • 工具
        • Python runtime visualize (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):虚拟环境管理
      • 包
        • 格式化:Auto formatters for Python (opens new window)
          • autopep8 (opens new window)
          • black (opens new window)
        • lint
          • pylint (opens new window)
          • flake8 (opens new window)
          • mypy (opens new window):带类型检查
        • 测试
          • pytest (opens new window):测试
          • coverage (opens new window):代码覆盖率
      • PyPI 榜单
        • Python Wheels (opens new window)
        • Top PyPI Packages (opens new window)
        • PyPI Stats (opens new window)
      • 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

      # pipenv

      pip install pipenv
      pipenv --help
      pipenv shell
      python --version
      
      1
      2
      3
      4

      # REPL, script

      python
      >>> import this
      >>> print('hello world')
      >>> exit()
      
      python script.py
      
      1
      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) 在 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) [y for x in data if (y := f(x))]
        • 运算符优先级 (opens new window)
      • 序列
        • 切片 (opens new window) a[:], a[:-1], a[0:10:1]
          • 索引越界
          • 负数索引
        • 序列的比较 (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
            • 浮点数算不准 (opens new window)
          • complex: 1+2j
        • 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)
          • 原始字符串 (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
        • None (opens new window)
        • 序列类型 (opens new window)
          • list: [1, 2, 3]
          • tuple (opens new window): (1,), (1, 2, 3)
            • 括号可以省略
            • 元组打包 - 序列解包 a, b = 1, 2
        • 集合 (opens new window)
          • set: {'a', 'b', 'c'}
          • frozenset
        • 映射/字典 (opens new window)
          • dict: {'a': 1, 'b': 2, 'c': 3}
      • 一些特性
        • 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)
      • Python 多重继承 super()的 MRO 坑 (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)
        • 数学
          • math (opens new window):基础数学运算
          • decimal (opens new window):浮点运算
          • fractions (opens new window):分数
          • random (opens new window):随机工具
        • array (opens new window):数组
        • datetime (opens new window):时间和日期
        • re (opens new window):正则表达式
        • json (opens new window):(注意到 Python 的 dict 和 JS 的 object 不一样)
      • I/O
        • 读写文件 (opens new window)
        • open (opens new window)
        • os (opens new window)

      # 类型提示

      typing (opens new window)

      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
      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

      # 高级使用

      • iterator (opens new window) __iter__, __next__
      • generator (opens new window) yield
      • decorator (opens new window) @f
      • 描述器(getter/setter)
        • 描述器使用指南 (opens new window)
        • property (opens new window)
      • 协程与任务 (opens new window)
        • coroutine (opens new window)
        • awaitable (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

      # 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

      # 类实例属性查找

      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
      #编程语言#Python#基础
      上次更新: Jan 29, 2022 6:01 PM
      最近更新
      01
      Linux Shell 快速入门笔记
      11-18
      02
      我的 Web 前端开发知识体系 (2022)
      01-29
      03
      游戏环境研究笔记(2022-01)
      01-16
      更多文章>
      Theme by Vdoing | Copyright © 2019-2022 Seognil LC | MIT License
      • 跟随系统
      • 浅色模式
      • 深色模式
      • 阅读模式