Python

精选 Python 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。 Python 3 编程语言单页极速参考与核心命令备忘单。

#入门指南

#Hello World 示例 (Hello World)

>>> print("Hello, World!")
Hello, World!

Python 著名的 "Hello World" 入门程序

#变量声明 (Variables)

age = 18      # age 变量类型为 int
name = "John" # name 变量类型为 str
print(name)

注意:Python 无法在不赋值的情况下声明变量。

#数据类型概览 (Data Types)

类型 分类名称
str 文本 (Text)
int, float, complex 数值 (Numeric)
list, tuple, range 序列 (Sequence)
dict 映射/字典 (Mapping)
set, frozenset 集合 (Set)
bool 布尔 (Boolean)
bytes, bytearray, memoryview 二进制 (Binary)

参阅: 数据类型详解

#字符串切片 (Slicing String)

>>> msg = "Hello, World!"
>>> print(msg[2:5])
llo

参阅: 字符串操作

#列表操作 (Lists)

mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
    print(item) # 输出 1, 2

参阅: 列表详解

#条件控制 (If Else)

num = 200
if num > 0:
    print("num 大于 0")
else:
    print("num 不大于 0")

参阅: 流程控制

#循环语句 (Loops)

for item in range(6):
    if item == 3: break
    print(item)
else:
    print("终于循环完毕!")

参阅: 循环详解

#函数定义 (Functions)

>>> def my_function():
...     print("来自函数的招呼")
...
>>> my_function()
来自函数的招呼

参阅: 函数详解

#文件读写操作 (File Handling)

with open("myfile.txt", "r", encoding='utf8') as file:
    for line in file:
        print(line)

参阅: 文件操作详解

#算术运算符 (Arithmetic)

result = 10 + 30 # => 40
result = 40 - 10 # => 30
result = 50 * 5  # => 250
result = 16 / 4  # => 4.0 (浮点数除法)
result = 16 // 4 # => 4 (整数整除/向下取整)
result = 25 % 2  # => 1 (取余数)
result = 5 ** 3  # => 125 (幂运算)

其中 / 表示两数相除的商(浮点数),// 表示向下取整的整数商。

#自增与加法赋值 (Plus-Equals)

counter = 0
counter += 10           # => 10
counter = 0
counter = counter + 10  # => 10

message = "Part 1."

# => Part 1.Part 2.
message += "Part 2."

#f-Strings 格式化 (Python 3.6+)

>>> website = 'warpnav.com'
>>> f"Hello, {website}"
"Hello, warpnav.com"

>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'

参阅: Python F-Strings

#Python 内置数据类型

#字符串 (Strings)

hello = "Hello World"
hello = 'Hello World'

multi_string = """多行字符串
支持跨多行输入
文本内容"""

参阅: 字符串操作

#数值类型 (Numbers)

x = 1    # int 整型
y = 2.8  # float 浮点型
z = 1j   # complex 复数型

>>> print(type(x))
<class 'int'>

#布尔类型 (Booleans)

my_bool = True
my_bool = False

bool(0)     # => False
bool(1)     # => True

#列表 (Lists)

list1 = ["apple", "banana", "cherry"]
list2 = [True, False, False]
list3 = [1, 5, 7, 9, 3]
list4 = list((1, 5, 7, 9, 3))

参阅: 列表详解

#元组 (Tuple)

my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3))

tupla = (1, 2, 3, 'python')

print(tupla[0])       # 输出: 1
print(tupla.count(1)) # 统计元素出现次数
print(tupla.index(2)) # 查找元素索引

tupla1 = (1, 2, 3)
tupla2 = ('a', 'b')

len(tuple) → 返回元素总个数。
in → 检查元素是否存在于元组中。
拼接 (+) → 合并两个元组。
重复 (*) → 重复元组元素。
切片 (tuple[start:end]) → 提取子元组。

print(len(tupla1))       # 输出: 3
print(2 in tupla1)       # 输出: True
print(tupla1 + tupla2)   # 输出: (1, 2, 3, 'a', 'b')
print(tupla1[1:])        # 输出: (2, 3)

# 解包 (Unpacking)
a, b, c, d = tupla   # 依次解包赋值给变量

类似于列表,但属于不可变类型 (Immutable)

#集合 (Set)

set1 = {"a", "b", "c"}
set2 = set(("a", "b", "c"))

包含唯一元素的无序集合 (Set)

#字典 (Dictionary)

>>> empty_dict = {}
>>> a = {"one": 1, "two": 2, "three": 3}
>>> a["one"]
1
>>> a.keys()
dict_keys(['one', 'two', 'three'])
>>> a.values()
dict_values([1, 2, 3])
>>> a.update({"four": 4})
>>> a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>> a['four']
4

键值对 (Key-Value) 结构,类似于 JSON 对象

#类型转换 (Casting)

#转换为整型 (Integers)

x = int(1)   # x 为 1
y = int(2.8) # y 为 2 (截断小数)
z = int("3") # z 为 3

#转换为浮点型 (Floats)

x = float(1)     # x 为 1.0
y = float(2.8)   # y 为 2.8
z = float("3")   # z 为 3.0
w = float("4.2") # w 为 4.2

#转换为字符串 (Strings)

x = str("s1") # x 为 's1'
y = str(2)    # y 为 '2'
z = str(3.0)  # z 为 '3.0'

#Python 进阶数据结构

#堆队列 (Heaps)

import heapq

myList = [9, 5, 4, 1, 3, 2]
heapq.heapify(myList) # 将 myList 转化为最小堆 (Min Heap)
print(myList)    # => [1, 3, 2, 5, 9, 4]
print(myList[0]) # 堆顶第一个值永远是堆中的最小值

heapq.heappush(myList, 10) # 压入元素 10
x = heapq.heappop(myList)  # 弹出并返回最小元素
print(x)                   # => 1

#借助取反实现最大堆 (Max Heap)

myList = [9, 5, 4, 1, 3, 2]
myList = [-val for val in myList] # 乘以 -1 取反
heapq.heapify(myList)

x = heapq.heappop(myList)
print(-x) # => 9 (取出后再乘以 -1 还原)

堆是满足父节点小于等于子节点值的二叉树,用于快速获取最小值/最大值。时间复杂度:堆化为 O(n),压入/弹出为 O(log n)。参阅:heapq 模块官方文档

#栈与双端队列 (Stacks & Queues)

from collections import deque

q = deque()          # 创建空双端队列
q = deque([1, 2, 3]) # 带初始值的双端队列

q.append(4)     # 右侧入队/入栈
q.appendleft(0) # 左侧入队
print(q)    # => deque([0, 1, 2, 3, 4])

x = q.pop()     # 右侧出队/出栈并返回
y = q.popleft() # 左侧出队并返回
print(x)    # => 4
print(y)    # => 0
print(q)    # => deque([1, 2, 3])

q.rotate(1) # 循环右移 1 步
print(q)    # => deque([3, 1, 2])

deque 是双端队列,两端的入队/出队操作时间复杂度均为 O(1)。常用于高效实现栈 (Stack) 与队列 (Queue)。参阅:deque 官方文档

#Python 字符串常用操作

#类似数组的索引访问

>>> hello = "Hello, World"
>>> print(hello[1])
e
>>> print(hello[-1])
d

获取指定位置索引或倒数第 1 个字符

#字符遍历 (Looping)

>>> for char in "foo":
...     print(char)
f
o
o

遍历字符串 "foo" 中的每个字符

#字符串切片详解 (Slicing)

 ┌───┬───┬───┬───┬───┬───┬───┐
 | m | y | b | a | c | o | n |
 └───┴───┴───┴───┴───┴───┴───┘
 0   1   2   3   4   5   6   7
-7  -6  -5  -4  -3  -2  -1

>>> s = 'mybacon'
>>> s[2:5]
'bac'
>>> s[0:2]
'my'
>>> s = 'mybacon'
>>> s[:2]
'my'
>>> s[2:]
'bacon'
>>> s[:2] + s[2:]
'mybacon'
>>> s[:]
'mybacon'
>>> s = 'mybacon'
>>> s[-5:-1]
'baco'
>>> s[2:6]
'baco'

#带步长切片 (Stride)

>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::5]
'11111'
>>> s[4::5]
'55555'
>>> s[::-5]
'55555'
>>> s[::-1]
'5432154321543215432154321'

#获取字符串长度 (Length)

>>> hello = "Hello, World!"
>>> print(len(hello))
13

使用 len() 函数获取字符串长度

#字符串重复

>>> s = '===+'
>>> n = 8
>>> s * n
'===+===+===+===+===+===+===+===+'

#字符串包含判断

>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in 'I saw The Holy Grail!'
True

#字符串拼接

>>> s = 'spam'
>>> t = 'egg'
>>> s + t
'spamegg'
>>> 'spam' 'egg'
'spamegg'

#字符串格式化

name = "John"
print("Hello, %s!" % name)
name = "John"
age = 23
print("%s is %d years old." % (name, age))

#format() 方法

txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2 = "My name is {0}, I'm {1}".format("John", 36)
txt3 = "My name is {}, I'm {}".format("John", 36)

#控制台输入 (Input)

>>> name = input("请输入你的名字: ")
请输入你的名字: Tom
>>> name
'Tom'

从控制台获取用户输入数据

#字符串连接 (Join)

>>> "#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

#检查后缀 (Endswith)

>>> "Hello, world!".endswith("!")
True

#Python f-Strings 格式化 (Python 3.6+)

#f-Strings 基础用法

>>> website = 'warpnav.com'
>>> f"Hello, {website}"
"Hello, warpnav.com"

>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'

>>> f"""He said {"I'm John"}"""
"He said I'm John"

>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'

>>> name = 'Eric'
>>> age = 27
>>> f"""Hello!
...     I'm {name}.
...     I'm {age}."""
"Hello!\n    I'm Eric.\n    I'm 27."

Python 3.6+ 支持的 f-Strings 格式化语法。参阅:Formatted string literals 官方文档

#f-Strings 填充与对齐

>>> f'{"text":10}'     # 指定宽度 [width]
'text      '
>>> f'{"test":*>10}'   # 左侧填充
'******test'
>>> f'{"test":*<10}'   # 右侧填充
'test******'
>>> f'{"test":*^10}'   # 居中填充
'***test***'
>>> f'{12345:0>10}'    # 前导零填充
'0000012345'

#f-Strings 数值类型格式化

>>> f'{10:b}'        # 二进制 (Binary)
'1010'
>>> f'{10:o}'        # 八进制 (Octal)
'12'
>>> f'{200:x}'       # 十六进制小写
'c8'
>>> f'{200:X}'       # 十六进制大写
'C8'
>>> f'{345600000000:e}' # 科学计数法
'3.456000e+11'
>>> f'{65:c}'       # ASCII 字符类型
'A'
>>> f'{10:#b}'      # 带有前缀标志 (0b)
'0b1010'
>>> f'{10:#o}'      # 带有前缀标志 (0o)
'0o12'
>>> f'{10:#x}'      # 带有前缀标志 (0x)
'0xa'

#f-Strings 其他格式化技巧

>>> f'{-12345:0=10}'  # 负数填充
'-000012345'
>>> f'{12345:010}'    # 快捷补零
'0000012345'
>>> f'{-12345:010}'
'-000012345'
>>> import math       # 保留小数精度
>>> math.pi
3.141592653589793
>>> f'{math.pi:.2f}'
'3.14'
>>> f'{1000000:,.2f}' # 千位分隔符
'1,000,000.00'
>>> f'{1000000:_.2f}'
'1_000_000.00'
>>> f'{0.25:0%}'      # 百分比格式化
'25.000000%'
>>> f'{0.25:.0%}'
'25%'

#f-Strings 正负号显示

>>> f'{12345:+}'      # 显式正负号 [sign]
'+12345'
>>> f'{-12345:+}'
'-12345'
>>> f'{-12345:+10}'
'    -12345'
>>> f'{-12345:+010}'
'-000012345'

#Python 列表常用操作

#列表定义 (Defining)

>>> li1 = []
>>> li1
[]
>>> li2 = [4, 5, 6]
>>> li2
[4, 5, 6]
>>> li3 = list((1, 2, 3))
>>> li3
[1, 2, 3]
>>> li4 = list(range(1, 11))
>>> li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#列表推导式与生成 (List Comprehension)

>>> list(filter(lambda x : x % 2 == 1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

>>> [x ** 2 for x in range (1, 11) if  x % 2 == 1]
[1, 9, 25, 49, 81]

>>> [x for x in [3, 4, 5, 6, 7] if x > 5]
[6, 7]

>>> list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))
[6, 7]

#追加元素 (Append)

>>> li = []
>>> li.append(1)
>>> li
[1]
>>> li.append(2)
>>> li
[1, 2]
>>> li.append(4)
>>> li
[1, 2, 4]
>>> li.append(3)
>>> li
[1, 2, 4, 3]

#列表切片 (List Slicing)

列表切片通用语法:

a_list[start:end]
a_list[start:end:step]

#基础切片

>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[2:5]
['bacon', 'tomato', 'ham']
>>> a[-5:-2]
['egg', 'bacon', 'tomato']
>>> a[1:4]
['egg', 'bacon', 'tomato']

#省略索引

>>> a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>> a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

#带步长切片

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[0:6:2]
['spam', 'bacon', 'ham']
>>> a[1:6:2]
['egg', 'tomato', 'lobster']
>>> a[6:0:-2]
['lobster', 'tomato', 'egg']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

#删除元素 (Remove)

>>> li = ['bread', 'butter', 'milk']
>>> li.pop()
'milk'
>>> li
['bread', 'butter']
>>> del li[0]
>>> li
['butter']

#索引访问 (Access)

>>> li = ['a', 'b', 'c', 'd']
>>> li[0]
'a'
>>> li[-1]
'd'
>>> li[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

#列表拼接与扩展 (Concatenating)

>>> odd = [1, 3, 5]
>>> odd.extend([9, 11, 13])
>>> odd
[1, 3, 5, 9, 11, 13]
>>> odd = [1, 3, 5]
>>> odd + [9, 11, 13]
[1, 3, 5, 9, 11, 13]

#排序与反转 (Sort & Reverse)

>>> li = [3, 1, 3, 2, 5]
>>> li.sort()
>>> li
[1, 2, 3, 3, 5]
>>> li.reverse()
>>> li
[5, 3, 3, 2, 1]

#统计频率 (Count)

>>> li = [3, 1, 3, 2, 5]
>>> li.count(3)
2

#列表重复 (Repeating)

>>> li = ["re"] * 3
>>> li
['re', 're', 're']

#Python 流程控制 (Flow Control)

#if/elif/else 基础条件语句

num = 5
if num > 10:
    print("num 明显大于 10。")
elif num < 10:
    print("num 小于 10。")
else:
    print("num 正好等于 10。")

#单行三元运算符 (Ternary Operator)

>>> a = 330
>>> b = 200
>>> r = "a" if a > b else "b"
>>> print(r)
a

#条件逻辑 (elif/is)

value = True
if not value:
    print("Value 为 False")
elif value is None:
    print("Value 为 None")
else:
    print("Value 为 True")

#模式匹配 (Match-Case) (Python 3.10+)

x = 1
match x:
  case 0:
    print("零")
  case 1:
    print("一")
  case _:
    print("其他数值")

#Python 循环结构 (Loops)

#for 基础循环

primes = [2, 3, 5, 7]
for prime in primes:
    print(prime)

输出: 2 3 5 7

#带索引索引遍历 (enumerate)

animals = ["dog", "cat", "mouse"]
# enumerate() 为可迭代对象添加计数器
for i, value in enumerate(animals):
    print(i, value)

输出: 0 dog 1 cat 2 mouse

#while 循环

x = 0
while x < 4:
    print(x)
    x += 1  # x = x + 1 的简写

输出: 0 1 2 3

#break 中断循环

x = 0
for index in range(10):
    x = index * 10
    if index == 5:
    	break
    print(x)

输出: 0 10 20 30 40

#continue 跳过本次循环

for index in range(3, 8):
    x = index * 10
    if index == 5:
    	continue
    print(x)

输出: 30 40 60 70

#range 生成范围序列

for i in range(4):
    print(i) # 输出: 0 1 2 3

for i in range(4, 8):
    print(i) # 输出: 4 5 6 7

for i in range(4, 10, 2):
    print(i) # 输出: 4 6 8

#多列表并行遍历 (zip)

words = ['Mon', 'Tue', 'Wed']
nums = [1, 2, 3]
# 使用 zip 打包为元组列表
for w, n in zip(words, nums):
    print('%d:%s, ' %(n, w))

输出: 1:Mon, 2:Tue, 3:Wed,

#for/else 结构

nums = [60, 70, 30, 110, 90]
for n in nums:
    if n > 100:
        print("%d 大于 100" %n)
        break
else:
    print("未找到大于 100 的数值!")

#字典遍历 (Dictionary Loops)

johndict = {
  "firstname": "John",
  "lastname": "Doe",
  "age": 30
  }

for key, value in johndict.items():
	print(f"{key} : {value}")

#Python 推导式 (Comprehensions)

#列表推导式 (List Comprehension)

languages = ["html", "go", "rust", "javascript", "python"]

newlist = [x for x in languages if "l" not in x]
print(newlist) # 输出: ['go', 'rust', 'javascript', 'python']

#字典推导式 (Dictionary Comprehension)

languages = ["html", "go", "rust", "javascript", "python"]

language_dict = {lang: ('l' not in lang) for lang in languages}
print(language_dict)
# 输出: {'html': False, 'go': True, 'rust': True, 'javascript': True, 'python': True}

#Python 函数 (Functions)

#基础函数定义

def hello_world():
    print('Hello, World!')

#返回值 (Return)

def add(x, y):
    print("x 为 %s, y 为 %s" %(x, y))
    return x + y

add(5, 6)    # => 11

#位置变长参数 (*args)

def varargs(*args):
    return args

varargs(1, 2, 3)  # => (1, 2, 3)

args 的类型为元组 (Tuple)

#关键字变长参数 (**kwargs)

def keyword_args(**kwargs):
    return kwargs

keyword_args(big="foot", loch="ness")

kwargs 的类型为字典 (Dict)

#返回多个值

def swap(x, y):
    return y, x

x, y = swap(1, 2)  # => x = 2, y = 1

#默认参数 (默认值)

def add(x, y=10):
    return x + y

add(5)      # => 15
add(5, 20)  # => 25

#匿名函数 (Lambda)

# => True
(lambda x: x > 2)(3)

# => 5
(lambda x, y: x ** 2 + y ** 2)(2, 1)

#装饰器 (@decorator)

# 在不改变原有函数代码的前提下修改或扩展函数/方法的行为

def handle_errors(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            return print(f"捕捉到异常 : {e}")
    return wrapper

@handle_errors
def divide(a, b):
    return a / b

divide(10, 0) # 输出 : 捕捉到异常 : division by zero

#Python 模块导入 (Modules)

#导入模块

import math
print(math.sqrt(16))  # => 4.0

#导入特定函数/属性

from math import ceil, floor
print(ceil(3.7))   # => 4.0
print(floor(3.7))  # => 3.0

#导入所有内容

from math import *

#模块别名 (Alias)

import math as m

math.sqrt(16) == m.sqrt(16) # => True

#查看模块函数与属性 (dir)

import math
dir(math)

#Python 文件读写操作 (File Handling)

#读取文件 (Read File)

#逐行读取

with open("myfile.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line)

#带行号读取 (enumerate)

file = open('myfile.txt', 'r', encoding="utf-8")
for i, line in enumerate(file, start=1):
    print("行号 %s: %s" % (i, line))

#字符串文件读写

#写入字符串

contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w+", encoding="utf-8") as file:
    file.write(str(contents))

#读取字符串内容

with open('myfile1.txt', "r+", encoding="utf-8") as file:
    contents = file.read()
print(contents)

#JSON 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 对象读写

#写入 JSON 数据

import json

contents = {"aa": 12, "bb": 21}
with open("myfile2.txt", "w+", encoding="utf-8") as file:
    file.write(json.dumps(contents))

#读取 JSON 数据

with open('myfile2.txt', "r+", encoding="utf-8") as file:
    contents = json.load(file)
print(contents)

#删除文件 (Delete File)

import os
os.remove("myfile.txt")

#文件存在性检查与删除

import os
if os.path.exists("myfile.txt"):
    os.remove("myfile.txt")
else:
    print("文件不存在!")

#删除目录 (Delete Folder)

import os
os.rmdir("myfolder")

#Python 面向对象与继承 (Classes & Inheritance)

#类定义与实例化

class MyNewClass:
    pass

# 实例化对象
my = MyNewClass()

#构造函数 (init)

class Animal:
    def __init__(self, voice):
        self.voice = voice

cat = Animal('喵喵')
print(cat.voice)    # => 喵喵

dog = Animal('汪汪')
print(dog.voice)    # => 汪汪

#实例方法 (Methods)

class Dog:

    # 类的成员方法
    def bark(self):
        print("汪汪叫")

charlie = Dog()
charlie.bark()   # => "汪汪叫"

#类变量 (Class Variables)

class MyClass:
    class_variable = "这是一个类变量!"

# 输出: 这是一个类变量!
print(MyClass.class_variable)

x = MyClass()

# 输出: 这是一个类变量!
print(x.class_variable)

#父类方法调用 (super)

class ParentClass:
    def print_test(self):
        print("父类方法")

class ChildClass(ParentClass):
    def print_test(self):
        print("子类方法")
        # 调用父类的 print_test()
        super().print_test()

>>> child_instance = ChildClass()
>>> child_instance.print_test()
子类方法
父类方法

#对象可读字符串表示 (repr)

class Employee:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name

john = Employee('John')
print(john)  # => John

#自定义异常类 (Custom Exceptions)

class CustomError(Exception):
    pass

#多态 (Polymorphism)

class ParentClass:
    def print_self(self):
        print('A')

class ChildClass(ParentClass):
    def print_self(self):
        print('B')

obj_A = ParentClass()
obj_B = ChildClass()

obj_A.print_self() # => A
obj_B.print_self() # => B

#方法重写 (Overriding)

class ParentClass:
    def print_self(self):
        print("父类实现")

class ChildClass(ParentClass):
    def print_self(self):
        print("子类重写")

child_instance = ChildClass()
child_instance.print_self() # => 子类重写

#类继承 (Inheritance)

class Animal:
    def __init__(self, name, legs):
        self.name = name
        self.legs = legs

class Dog(Animal):
    def sound(self):
        print("汪汪!")

Yoki = Dog("Yoki", 4)
print(Yoki.name) # => Yoki
print(Yoki.legs) # => 4
Yoki.sound()     # => 汪汪!

#静态方法 (@staticmethod)

class MyClass:
    @staticmethod
    def greet(name):
        return f"你好, {name}!"

# 无需实例化即可通过类直接调用
print(MyClass.greet("Alice"))  # => 你好, Alice!

# 也可以通过实例对象调用
obj = MyClass()
print(obj.greet("Bob"))        # => 你好, Bob!

#Python 类型注解 (Type Hints) (Python 3.5+)

#变量与参数注解

string: str = "ha"
times: int = 3

def say(name: str, start: str = "Hi"):
    return start + ", " + name

print(say("Python"))  # => Hi, Python

#容器数据类型注解

from typing import Dict, Tuple, List

bill: Dict[str, float] = {
    "apple": 3.14,
    "watermelon": 15.92,
}
completed: Tuple[str] = ("DONE",)
succeeded: Tuple[int, str] = (1, "SUCCESS")
codes: List[int] = [0, 1, -1, -2]

#容器数据类型注解 (Python 3.10+)

bill: dict[str, float] = {
    "apple": 3.14,
    "watermelon": 15.92,
}
completed: tuple[str] = ("DONE",)
succeeded: tuple[int, str] = (1, "SUCCESS")
codes: list[int] = [0, 1, -1, -2]

#变长参数类型注解

def calc_summary(*args: int):
    return sum(args)

print(calc_summary(3, 1, 4))  # => 8

所有传入参数的类型均为 int

#函数返回值类型注解

def say_hello(name) -> str:
    return "Hello, " + name

var = "Python"
print(say_hello(var))  # => Hello, Python

#多类型联合返回值 (Union)

from typing import Union

def resp200(meaningful) -> Union[int, str]:
    return "OK" if meaningful else 200

返回值类型可能是 int 或 str

#关键字变长参数类型注解

def calc_summary(**kwargs: int):
    return sum(kwargs.values())

print(calc_summary(a=1, b=2))  # => 3

所有关键字参数的值类型均为 int

#多返回值元组注解

def resp200() -> (int, str):
    return 200, "OK"

returns = resp200()
print(returns)  # => (200, 'OK')

#多类型联合返回值简写 (Python 3.10+)

def resp200(meaningful) -> int | str:
    return "OK" if meaningful else 200

Python 3.10+ 原生语法

#类属性类型注解

class Employee:
    name: str
    age: int

    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.graduated: bool = False

#返回类自身的实例注解

class Employee:
    name: str

    def set_name(self, name) -> "Employee":
        self.name = name
        return self

    def copy(self) -> 'Employee':
        return type(self)(self.name)

#返回 Self 类型注解 (Self instance 3.11+)

from typing import Self

class Employee:
    name: str
    age: int

    def set_name(self: Self, name) -> Self:
        self.name = name
        return self

#泛型类型注解 (Type & Generic)

from typing import TypeVar, Type

T = TypeVar("T")

# mapper 是一个类型,如 int, str, MyClass 等
# default 是 T 类型的实例对象,如 314, "string", MyClass() 等
def converter(raw, mapper: Type[T], default: T) -> T:
    try:
        return mapper(raw)
    except:
        return default

raw: str = input("请输入整数: ")
result: int = converter(raw, mapper=int, default=0)

#可调用对象/函数类型注解 (Callable)

from typing import TypeVar, Callable, Any

T = TypeVar("T")

def converter(raw, mapper: Callable[[Any], T], default: T) -> T:
    try:
        return mapper(raw)
    except:
        return default

def is_success(value) -> bool:
    return value in (0, "OK", True, "success")

resp = dict(code=0, message="OK", data=[])
successed: bool = converter(resp["message"], mapper=is_success, default=False)

#Python 运算符与特性

#海象运算符 (Walrus Operator :=)

values = [1, "text", True, "", 2]
i = 0

# 赋值给变量的同时在布尔表达式中进行逻辑判断
while (data := values[i]):

    print(data, end=",")
    i = i + 1

# 预期输出: 1, "text", True

#Python 日期与时间处理 (Date & Time)

#获取当前日期与时间

import datetime

now = datetime.datetime.now()
print(now)  # 输出示例: 2024-04-27 14:35:22.123456

#创建特定日期/时间对象

import datetime

# 创建日期对象
d = datetime.date(2024, 4, 27)
print(d)  # 2024-04-27

# 创建时间对象
t = datetime.time(15, 30, 45)
print(t)  # 15:30:45

# 创建日期时间对象
dt = datetime.datetime(2024, 4, 27, 15, 30, 45)
print(dt)  # 2024-04-27 15:30:45

#日期格式化与解析转换 (strftime / strptime)

import datetime

# 将文本字符串解析为 datetime 对象
date_str = "2024-04-27 14:00"
dt_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M")
print(dt_obj)  # 2024-04-27 14:00:00

# 将 datetime 对象格式化为指定字符串
formatted_str = dt_obj.strftime("%d/%m/%Y %H:%M")
print(formatted_str)  # 27/04/2024 14:00

#时间戳与 Unix 时间

import datetime

# 获取当前 Unix 时间戳
timestamp = datetime.datetime.now().timestamp()
print(timestamp)  # 例如: 1714188922.123456

# 将时间戳转换回 datetime 对象
dt_from_timestamp = datetime.datetime.fromtimestamp(timestamp)
print(dt_from_timestamp)

#日期时间差与加减 (timedelta)

import datetime

date1 = datetime.date(2024, 4, 27)
date2 = datetime.date(2024, 5, 1)

delta = date2 - date1
print(delta.days)  # 相差 4 天

# 使用 timedelta 进行日期加减计算
new_date = date1 + datetime.timedelta(days=10)
print(new_date)  # 2024-05-07

#Python 综合高级技巧 (Miscellaneous)

#注释与文档字符串 (Docstrings)

# 这是单行注释
""" 使用三个双引号包裹多行字符串,
    通常用作函数或类的文档说明 (Docstring)。
"""

#生成器 (Generators)

def double_numbers(iterable):
    for i in iterable:
        yield i + i

生成器 (yield) 可以帮助你轻松实现惰性计算 (Lazy Evaluation)。

#生成器转列表 (Generator to List)

values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)

# => [-1, -2, -3, -4, -5]
print(gen_to_list)

#异常处理机制 (try/except/else/finally)

try:
    # 使用 raise 主动抛出异常
    raise IndexError("这是一个索引超出范围异常")
except IndexError as e:
    pass                 # pass 表示空指令,通常在此处做错误恢复处理
except (TypeError, NameError):
    pass                 # 可以同时捕获多种异常类型
else:                    # 可选子句:当 try 块中未触发任何异常时执行
    print("一切正常运行!")
finally:                 # 无论是否发生异常都必然执行的收尾逻辑
    print("在此处统一清理释放系统资源")

#分发器设计模式 (Dispatcher Pattern)

# 分发器模式允许根据用户输入或运行时条件动态选择和执行对应函数

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return '错误: 除数不能为零'
    return x / y

# 分发器字典:将操作名称映射到其对应的处理函数
operations = {
    'add': add,
    'subtract': subtract,
    'multiply': multiply,
    'divide': divide
}

# 动态分发函数
def dispatcher(operation_name, x, y):
    func = operations.get(operation_name)
    if func:
        return func(x, y)
    else:
        return f"未知操作指令: {operation_name}"

# 调用示例
print(dispatcher('add', 5, 3))        # 输出: 8
print(dispatcher('multiply', 4, 2))   # 输出: 8
print(dispatcher('divide', 10, 0))    # 输出: 错误: 除数不能为零
print(dispatcher('mod', 10, 3))       # 输出: 未知操作指令: mod