Python 语言特性梳理
类型系统
Python 是一门动态类型语言,其类型系统的特点
动态类型 :变量不需要声明类型,可以指向任何类型的对象
强类型 :不同类型之间不会自动转换(除了数值类型)
鸭子类型 :关注对象的行为而非类型,即面向接口编程
渐进式类型 :可以选择性地添加类型提示,不影响运行时行为
基本类型
Python 内置了以下基本类型:
int
整数,无精度限制
42, -7, 0
float
浮点数,双精度
3.14, -0.001, 1e-10
bool
布尔值,int 的子类
True, False
str
字符串,Unicode 文本
'hello', "world"
bytes
字节序列
b'hello'
NoneType
空值类型
None
1 2 3 4 5 6 7 x: int = 42 y: float = 3.14 flag: bool = True name: str = "Python" data: bytes = b"data" nothing: None = None
类型提示
Python 3.6+ 支持变量注解语法,PEP 526 引入了这种语法:
1 2 3 4 5 6 7 8 9 10 name: str = "Alice" age: int = 30 height: float = 1.75 from typing import List , Dict scores: List [int ] = [90 , 85 , 95 ] person: Dict [str , str ] = {"name" : "Bob" , "city" : "Beijing" }
字符串 (String)
字符串是不可变 的字符序列:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 text = "Hello, World!" print (text[0 ]) print (text[7 :12 ]) print (text.lower()) print (text.upper()) print (text.split(', ' )) print ('-' .join(['a' , 'b' , 'c' ])) name = "Alice" age = 30 print (f"Name: {name} , Age: {age} " ) print ("Name: {}, Age: {}" .format (name, age))
类 && 接口
TODO
数据类 (dataclass)
dataclass 是 Python 3.7+
引入的装饰器,用于简化类的定义:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from dataclasses import dataclassfrom typing import List @dataclass class Person : name: str age: int emails: List [str ] = None def __post_init__ (self ): if self .emails is None : self .emails = [] person = Person("Alice" , 30 ) print (person)
类型判断与检查
运行时类型判断:
1 2 3 4 5 6 7 8 9 10 print (type (42 )) print (type ([])) if isinstance (x, (int , float )): print ("x is a number" ) print (issubclass (bool , int ))
特殊类型
Callable 类型
使用 Callable 表示可调用对象:
1 2 3 4 5 6 7 8 9 from typing import Callable def apply (func: Callable [[int , int ], int ], x: int , y: int ) -> int : return func(x, y) def add (a: int , b: int ) -> int : return a + b result = apply(add, 3 , 5 )
NoReturn 类型
NoReturn 用于表示永远不会正常返回的函数:
1 2 3 4 5 6 7 8 from typing import NoReturndef raise_error () -> NoReturn: raise ValueError("This function never returns" ) def exit_program () -> NoReturn: import sys sys.exit(1 )
容器
Python 提供了丰富的容器类型,用于存储和组织数据。
序列类型
序列是 Python
中最基本的数据结构,按照顺序存储 元素。
列表 (List)
列表是可变 序列,用方括号 [] 表示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 numbers = [1 , 2 , 3 , 4 , 5 ] fruits = ['apple' , 'banana' , 'orange' ] mixed = [1 , 'hello' , 3.14 , True ] numbers.append(6 ) numbers.insert(0 , 0 ) numbers.extend([7 , 8 ]) x = numbers.pop() numbers.remove(3 ) numbers[0 ] = 10 print (numbers[1 :4 ]) print (numbers[:3 ]) print (numbers[::2 ]) print (numbers[::-1 ])
使用数组代替列表
使用数组代替列表可以更节省内存空间。
1 2 3 4 5 6 7 8 9 10 import arraylist_nums = [1 , 2 , 3 , 4 , 5 ] arr_nums = array.array('i' , [1 , 2 , 3 , 4 , 5 ]) print (sys.getsizeof(list_nums)) print (sys.getsizeof(arr_nums))
元组 (Tuple)
元组是不可变 序列,用圆括号 ()
表示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 coordinates = (3 , 4 ) single = (42 ,) empty = () x, y = coordinates from collections import namedtuplePoint = namedtuple('Point' , ['x' , 'y' ]) p = Point(11 , 22 ) print (p.x, p.y) from typing import NamedTupleclass Point (NamedTuple ): x: float y: float p = Point(1.5 , 2.5 )
字典 (Dict)
字典是键值对的集合 ,用花括号 {}
表示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 person = { 'name' : 'Alice' , 'age' : 30 , 'city' : 'Beijing' } print (person['name' ]) print (person.get('email' , 'N/A' )) person['email' ] = 'alice@example.com' person['age' ] = 31 del person['city' ] print (person.keys()) print (person.values()) print (person.items()) squares = {x: x**2 for x in range (6 )} dict1 = {'a' : 1 , 'b' : 2 } dict2 = {'c' : 3 , 'd' : 4 } merged = dict1 | dict2
defaultdict
defaultdict 在访问不存在的键时返回默认值:
1 2 3 4 5 6 7 8 9 10 11 12 from collections import defaultdictdd = defaultdict(list ) dd['fruits' ].append('apple' ) dd['fruits' ].append('banana' ) counter = defaultdict(int ) counter['apple' ] += 1 counter['banana' ] += 2
集合类型
集合是无序不重复 元素的集合,用花括号 {}
表示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 numbers = {1 , 2 , 3 , 4 , 5 } fruits = set (['apple' , 'banana' , 'orange' ]) numbers.add(6 ) numbers.discard(3 ) numbers.remove(4 ) a = {1 , 2 , 3 , 4 } b = {3 , 4 , 5 , 6 } print (a | b) print (a & b) print (a - b) print (a ^ b) squares = {x**2 for x in range (6 )}
迭代器
TODO
生成器
1 2 3 4 5 6 7 8 9 10 11 def get_squares_list (n ): return [i**2 for i in range (n)] def get_squares_gen (n ): for i in range (n): yield i**2 sum_of_squares = sum (i**2 for i in range (1000000 ))
常用语法以及操作
推导式与生成器表达式
列表推导式
列表推导式提供简洁的方式创建列表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 numbers = [x for x in range (10 )] evens = [x for x in range (10 ) if x % 2 == 0 ] squares = [x**2 for x in range (6 )] matrix = [[i*j for j in range (3 )] for i in range (3 )] colors = ['black' , 'white' ] sizes = ['S' , 'M' , 'L' ] tshirts = [(c, s) for c in colors for s in sizes]
生成器表达式
生成器表达式不创建列表,而是生成一个生成器对象,使用圆括号 ,节省内存:
1 2 3 4 5 6 7 8 9 10 11 12 gen = (x**2 for x in range (10 )) for val in gen: print (val) sum_of_squares = sum (x**2 for x in range (10 )) max_value = max (x**2 for x in range (10 ))
字典和集合推导式
1 2 3 4 5 6 7 8 9 10 11 word_lengths = {word: len (word) for word in ['apple' , 'banana' , 'cherry' ]} inverted = {v: k for k, v in word_lengths.items()} unique_lengths = {len (word) for word in ['apple' , 'banana' , 'cherry' ]}
序列拆包
基本拆包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 a, b, c = (1 , 2 , 3 ) x, y, z = [10 , 20 , 30 ] a, b = b, a first, *rest = [1 , 2 , 3 , 4 , 5 ] *head, last = [1 , 2 , 3 , 4 , 5 ] first, *middle, last = [1 , 2 , 3 , 4 , 5 ]
嵌套拆包
1 2 3 4 5 6 7 8 (a, b), (c, d) = (1 , 2 ), (3 , 4 ) person = ('Alice' , [20 , 'Python' ]) name, (age, language) = person
在函数调用中使用拆包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 numbers = [1 , 2 , 3 ] print (*numbers) def greet (name, age ): print (f"Name: {name} , Age: {age} " ) person = {'name' : 'Bob' , 'age' : 25 } greet(**person) list1 = [1 , 2 ] list2 = [3 , 4 ] combined = [*list1, *list2] dict1 = {'a' : 1 } dict2 = {'b' : 2 } merged = {**dict1, **dict2}
切片操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 seq = [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] print (seq[2 :5 ]) print (seq[:5 ]) print (seq[5 :]) print (seq[::2 ]) print (seq[::-1 ]) slice_obj = slice (2 , 5 , 2 ) print (seq[slice_obj]) seq[2 :5 ] = [20 , 30 , 40 ] del seq[2 :5 ]
条件表达式
1 2 3 4 5 6 7 value = 10 result = "positive" if value > 0 else "non-positive" age = 25 category = "child" if age < 13 else "teen" if age < 20 else "adult"
循环
for 循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 for item in [1 , 2 , 3 ]: print (item) for index, value in enumerate (['a' , 'b' , 'c' ]): print (index, value) for key, value in person.items(): print (key, value) names = ['Alice' , 'Bob' , 'Charlie' ] ages = [25 , 30 , 35 ] for name, age in zip (names, ages): print (f"{name} : {age} " ) for item in reversed ([1 , 2 , 3 ]): print (item) for item in sorted ([3 , 1 , 2 ]): print (item)
while 循环
1 2 3 4 5 6 7 8 9 10 11 count = 0 while count < 5 : print (count) count += 1 count = 0 while count < 5 : count += 1 else : print ("Loop completed" )
模式匹配 (Python 3.10+)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 match value: case 1 : print ("One" ) case 2 | 3 : print ("Two or three" ) case _: print ("Something else" ) def describe_point (point ): match point: case (0 , 0 ): return "Origin" case (x, 0 ): return f"X-axis at {x} " case (0 , y): return f"Y-axis at {y} " case (x, y): return f"Point at ({x} , {y} )" def handle_config (config ): match config: case {'type' : 'user' , 'name' : name}: return f"User: {name} " case {'type' : 'admin' , 'name' : name, 'permissions' : perms}: return f"Admin {name} with {perms} " case _: return "Unknown config" @dataclass class Point : x: float y: float def greet (point ): match point: case Point(x=0 , y=0 ): return "At origin" case Point(x=x, y=y): return f"At ({x} , {y} )"
函数定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 def greet (name ): return f"Hello, {name} !" def greet (name, greeting="Hello" ): return f"{greeting} , {name} !" def sum_all (*args ): return sum (args) def print_info (**kwargs ): for key, value in kwargs.items(): print (f"{key} : {value} " ) def func (a, b, /, c, d, *, e, f ): pass def add (x: int , y: int ) -> int : return x + y
Lambda 表达式
1 2 3 4 5 6 7 8 9 10 11 12 add = lambda x, y: x + y print (add(3 , 5 )) numbers = [1 , 2 , 3 , 4 , 5 ] squared = list (map (lambda x: x**2 , numbers)) evens = list (filter (lambda x: x % 2 == 0 , numbers)) students = [('Alice' , 25 ), ('Bob' , 20 ), ('Charlie' , 30 )] students.sort(key=lambda s: s[1 ])
装饰器基础
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 def my_decorator (func ): def wrapper (): print ("Before function call" ) func() print ("After function call" ) return wrapper @my_decorator def say_hello (): print ("Hello!" ) def repeat (times ): def decorator (func ): def wrapper (*args, **kwargs ): for _ in range (times): func(*args, **kwargs) return wrapper return decorator @repeat(3 ) def greet (name ): print (f"Hello, {name} !" ) greet("Alice" )
异常
Python 使用异常来处理错误和异常情况。
基本的异常层次结构
1 2 3 4 5 6 classDiagram BaseException <|-- SystemExit BaseException <|-- GeneratorExit BaseException <|-- Exception Exception <|-- RuntimeError
捕获异常
使用 try-except-else-finally 捕获异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 try : result = risky_operation() except ValueError as e: print (f"Value error: {e} " ) except Exception as e: print (f"Unexpected error: {e} " ) else : print (f"Success: {result} " ) finally : cleanup()
抛出异常
使用 raise <exception> 抛出异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 if age < 0 : raise ValueError("Age cannot be negative" ) error = ValueError("Invalid value" ) raise errortry : risky_operation() except Exception as e: log_error(e) raise try : risky_operation() except Exception as e: raise ValueError("Operation failed" ) from e
自定义异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class CustomError (Exception ): """自定义异常基类""" pass class ValidationError (CustomError ): """验证错误""" def __init__ (self, message, field=None ): self .field = field super ().__init__(message) def validate_age (age ): if age < 0 : raise ValidationError("Age cannot be negative" , field="age" ) if age > 150 : raise ValidationError("Age is unrealistic" , field="age" ) return True try : validate_age(-5 ) except ValidationError as e: print (f"Validation failed for {e.field} : {e} " )
异常链
1 2 3 4 5 6 7 8 9 10 11 try : data = load_config() except KeyError as e: raise ConfigError("Invalid configuration" ) from e try : data = load_config() except KeyError: raise ConfigError("Invalid configuration" ) from None
I/O 操作
一般使用 with-as
语句来访问资源,并在使用完资源对象后,关闭/释放资源。
文件读写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 with open ('file.txt' , 'r' , encoding='utf-8' ) as f: content = f.read() with open ('file.txt' , 'r' , encoding='utf-8' ) as f: for line in f: print (line.strip()) with open ('file.txt' , 'r' , encoding='utf-8' ) as f: lines = f.readlines() with open ('file.txt' , 'w' , encoding='utf-8' ) as f: f.write('Hello, World!\n' ) with open ('file.txt' , 'a' , encoding='utf-8' ) as f: f.write('New line\n' ) with open ('file.txt' , 'w' , encoding='utf-8' ) as f: f.writelines(['line1\n' , 'line2\n' , 'line3\n' ])
ContextManager
在资源使用完后,自动触发关闭/清理操作。
实现自定义资源类中的 __enter__ 和 __exit__
方法
使用 contextlib 中的 @contextmanager 装饰器
自定义资源类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class FileManager : def __init__ (self, filename, mode ): self .filename = filename self .mode = mode self .file = None def __enter__ (self ): self .file = open (self .filename, self .mode) return self .file def __exit__ (self, exc_type, exc_val, exc_tb ): if self .file: self .file.close() return False with FileManager('file.txt' , 'r' ) as f: data = f.read()
@contextmanager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from contextlib import contextmanager@contextmanager def managed_resource (): resource = acquire_resource() try : yield resource finally : release_resource(resource) with managed_resource() as resource: pass
并发
Python 提供了多种并发编程方式,包括多线程、多进程、异步 I/O
和协程。
GIL (全局解释器锁)
Python 使用 GIL 来确保同一时刻只有一个线程执行 Python
字节码。这意味着:
多线程不能在多核 CPU 上并行执行 CPU 密集型任务
多线程适合 I/O 密集型任务
CPU 密集型任务应使用多进程
多线程
多线程使用 threading 模块
基本线程使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import threadingimport timedef worker (name ): print (f"Worker {name} started" ) time.sleep(2 ) print (f"Worker {name} finished" ) t1 = threading.Thread(target=worker, args=('A' ,)) t2 = threading.Thread(target=worker, args=('B' ,)) t1.start() t2.start() t1.join() t2.join()
线程子类
1 2 3 4 5 6 7 8 9 10 11 12 13 import threadingclass MyThread (threading.Thread): def __init__ (self, name ): super ().__init__() self .name = name def run (self ): print (f"Thread {self.name} running" ) thread = MyThread("Worker" ) thread.start() thread.join()
线程池
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 from concurrent.futures import ThreadPoolExecutorimport timedef task (name ): time.sleep(1 ) return f"Task {name} completed" with ThreadPoolExecutor(max_workers=3 ) as executor: future1 = executor.submit(task, "A" ) future2 = executor.submit(task, "B" ) print (future1.result()) print (future2.result()) results = executor.map (task, ["A" , "B" , "C" ]) for result in results: print (result) from concurrent.futures import as_completedwith ThreadPoolExecutor(max_workers=3 ) as executor: futures = {executor.submit(task, name): name for name in ["A" , "B" , "C" ]} for future in as_completed(futures): name = futures[future] try : result = future.result() except Exception as e: print (f"{name} generated an exception: {e} " ) else : print (f"{name} : {result} " )
线程同步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 import threadinglock = threading.Lock() def safe_increment (): with lock: counter += 1 rlock = threading.RLock() def recursive_function (): with rlock: recursive_function() condition = threading.Condition() def consumer (): with condition: while not items_available: condition.wait() consume_item() def producer (): with condition: produce_item() condition.notify() semaphore = threading.Semaphore(3 ) def access_resource (): with semaphore: pass
线程本地数据
1 2 3 4 5 6 7 8 import threadinglocal_data = threading.local() def worker (): local_data.value = threading.current_thread().name print (f"Thread {local_data.value} " )
多进程
多进程使用 multiprocessing 模块,可以绕过
GIL,实现真正的并行执行。
基本进程使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import multiprocessingdef worker (name ): print (f"Worker {name} " ) return f"Result from {name} " if __name__ == '__main__' : p1 = multiprocessing.Process(target=worker, args=('A' ,)) p2 = multiprocessing.Process(target=worker, args=('B' ,)) p1.start() p2.start() p1.join() p2.join()
进程池
Pool
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from multiprocessing import Pooldef square (x ): return x ** 2 if __name__ == '__main__' : with Pool(processes=4 ) as pool: results = pool.map (square, range (10 )) result = pool.map_async(square, range (10 )) results = result.get() result = pool.apply(square, (5 ,)) result = pool.apply_async(square, (5 ,)) value = result.get() for result in pool.imap(square, range (10 )): print (result)
ProcessPoolExecutor
1 2 3 4 5 6 7 8 9 10 from concurrent.futures import ProcessPoolExecutordef cpu_bound_task (n ): return sum (i * i for i in range (n)) if __name__ == '__main__' : with ProcessPoolExecutor(max_workers=4 ) as executor: results = executor.map (cpu_bound_task, [10000 , 20000 , 30000 ]) for result in results: print (result)
进程间通信
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from multiprocessing import Process, Queue, Pipedef worker (q ): q.put("Hello from worker" ) if __name__ == '__main__' : q = Queue() p = Process(target=worker, args=(q,)) p.start() print (q.get()) p.join() def worker (conn ): conn.send("Hello" ) conn.close() if __name__ == '__main__' : parent_conn, child_conn = Pipe() p = Process(target=worker, args=(child_conn,)) p.start() print (parent_conn.recv()) p.join()
共享内存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from multiprocessing import Process, Value, Arraydef worker (n, a ): n.value = 3.1415927 for i in range (len (a)): a[i] = -a[i] if __name__ == '__main__' : num = Value('d' , 0.0 ) arr = Array('i' , range (10 )) p = Process(target=worker, args=(num, arr)) p.start() p.join() print (num.value) print (arr[:])
多协程
Python 3.4+ 引入了 asyncio 模块,支持协程,提供异步 I/O
支持。
1 2 3 4 5 6 7 8 9 10 import asyncioasync def hello (): print ("Hello" ) await asyncio.sleep(1 ) print ("World" ) asyncio.run(hello())
任务和并发
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import asyncioasync def task (name, delay ): print (f"Task {name} started" ) await asyncio.sleep(delay) print (f"Task {name} finished" ) return f"Result from {name} " async def main (): task1 = asyncio.create_task(task("A" , 2 )) task2 = asyncio.create_task(task("B" , 1 )) result1 = await task1 result2 = await task2 print (result1, result2) results = await asyncio.gather( task("A" , 2 ), task("B" , 1 ), task("C" , 3 ) ) print (results) asyncio.run(main())
超时和取消
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import asyncioasync def long_task (): await asyncio.sleep(10 ) return "Done" async def main (): try : result = await asyncio.wait_for(long_task(), timeout=2.0 ) except asyncio.TimeoutError: print ("Timeout!" ) task = asyncio.create_task(long_task()) await asyncio.sleep(1 ) task.cancel() try : await task except asyncio.CancelledError: print ("Task cancelled" ) asyncio.run(main())
同步原语
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import asyncioasync def worker_with_lock (lock, worker_id ): async with lock: print (f"Worker {worker_id} got lock" ) await asyncio.sleep(1 ) async def waiter (event ): print ("Waiting for event" ) await event.wait() print ("Event triggered" ) async def trigger (event ): await asyncio.sleep(1 ) event.set () print ("Event set" ) async def producer (queue ): for i in range (5 ): await queue.put(i) await asyncio.sleep(0.1 ) async def consumer (queue ): while True : item = await queue.get() print (f"Consumed: {item} " ) queue.task_done()
选择合适的并发模型
I/O 密集型
多协程(优先),多线程
CPU 密集型
多进程
高并发网络服务
多协程
内存管理
Python 使用自动内存管理,开发者通常不需要手动分配和释放内存。
变量与对象
Python 中变量是指向对象的引用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 a = [1 , 2 , 3 ] b = a b.append(4 ) print (a) a = [1 , 2 , 3 ] b = [1 , 2 , 3 ] print (a == b) print (a is b) a = 256 b = 256 print (a is b) a = 257 b = 257 print (a is b) a = "hello" b = "hello" print (a is b)
引用计数
Python 主要使用引用计数 来跟踪对象:
1 2 3 4 5 6 7 8 9 10 11 import sysa = [] print (sys.getrefcount(a)) b = a print (sys.getrefcount(a)) del bprint (sys.getrefcount(a))
del 语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 a = [1 , 2 , 3 ] b = a del a del ba = [1 , 2 , 3 , 4 , 5 ] del a[2 ] del a[1 :3 ] d = {'a' : 1 , 'b' : 2 , 'c' : 3 } del d['b' ]
深拷贝与浅拷贝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import copya = [[1 , 2 ], [3 , 4 ]] b = a.copy() b[0 ].append(5 ) print (a) a = [[1 , 2 ], [3 , 4 ]] b = copy.deepcopy(a) b[0 ].append(5 ) print (a) a = [1 , 2 , 3 ] b = copy.copy(a) c = copy.deepcopy(a)
高级特性
泛型
Python 使用 typing 模块支持泛型类型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from typing import List , Dict , Tuple , Set , Optional , Union numbers: List [int ] = [1 , 2 , 3 ] mapping: Dict [str , int ] = {"a" : 1 , "b" : 2 } coord: Tuple [float , float ] = (3.14 , 2.71 ) unique: Set [int ] = {1 , 2 , 3 } maybe: Optional [int ] = None value: Union [int , str ] = 42
TypeVar 和参数化泛型
对于更复杂的类型关系,可以使用 TypeVar:
1 2 3 4 5 6 7 8 9 from typing import TypeVar, List T = TypeVar('T' , int , float ) def first (items: List [T] ) -> T: return items[0 ] Comparable = TypeVar('Comparable' , bound=str )
Reference