300 字
1 分钟
Python 基础语法与核心概念
一、基本数据类型
1.1 数据类型一览
| 类型 | 示例 | 可变否 | 说明 |
|---|---|---|---|
| int | 42, 0b101, 0xFF | 任意精度整数 | |
| float | 3.14, 1e10 | 双精度浮点 | |
| complex | 3+4j | 复数 | |
| str | "hello", 'world' | Unicode 字符串 | |
| bytes | b'\xff\x00' | 字节序列 | |
| bool | True, False | True=1, False=0 | |
| list | [1, 2, 3] | 动态数组 | |
| tuple | (1, 2, 3) | 不可变序列 | |
| dict | {"a": 1} | 哈希表 | |
| set | {1, 2, 3} | 无序集合 | |
| frozenset | frozenset({1,2}) | 不可变集合 |
1.2 数值类型细节
# 整数缓存机制(-5 到 256)a = 256b = 256print(a is b) # True - 缓存范围内
a = 257b = 257print(a is b) # False - 超出缓存范围
# 进制表示hex_val = 0xFF # 十六进制 -> 255bin_val = 0b1010 # 二进制 -> 10oct_val = 0o17 # 八进制 -> 15
# 下划线分隔符(Python 3.6+)million = 1_000_000version = 3_.11_._version
# 复数c = 3 + 4jprint(c.real) # 3.0print(c.imag) # 4.0print(abs(c)) # 5.0 (模)1.3 字符串特性
# 字符串驻留s1 = "hello"s2 = "hello"print(s1 is s2) # True - 字符串驻留
# 使用格式化或拼接时可能不同s1 = "hello world"s2 = "hello " "world" # 编译时确定print(s1 is s2) # True
s1 = "hello"s2 = "".join(["hel", "lo"])print(s1 is s2) # False - 运行时拼接
# 原始字符串path = r"C:\Users\newfolder" # 不转义
# f-string (Python 3.6+)name = "Alice"age = 30print(f"Name: {name}, Age: {age}")print(f"Age in 5 years: {age + 5}")print(f"Math: {2 * 3 = }") # Python 3.8+: 2 * 3 = 6二、is 与 == 的区别
2.1 核心概念
| 运算符 | 含义 | 比较内容 |
|---|---|---|
== | 值相等 | 对象的内容/值 |
is | 身份相等 | 对象在内存中的地址 |
# 列表值相等但身份不同a = [1, 2, 3]b = [1, 2, 3]print(a == b) # True - 值相等print(a is b) # False - 对象不同
# 单例对象a = Noneb = Noneprint(a is b) # True - None 是单例2.2 整数缓存机制
# Python 整数缓存范围:-5 到 256# 这是 CPython 的实现细节,其他实现可能不同
# 缓存范围内的整数x = 256y = 256print(x is y) # True
# 超出缓存范围x = 257y = 257print(x is y) # False
# 编译时常量x = 1000y = 500 + 500 # 编译时计算结果print(x is y) # 可能为 True(Python 优化)
x = 1000y = 500z = x + 0print(x is z) # 可能为 False2.3 字符串驻留
# 简单字符串(字母、数字、下划线)会被驻留s1 = "hello"s2 = "hello"print(s1 is s2) # True
# 字符串拼接s1 = "hello world"s2 = "hello " "world" # 编译时合并print(s1 is s2) # True
s1 = "hello"s2 = "hel" + "lo"print(s1 is s2) # 可能为 True
# 运行时拼接不驻留s1 = "hello"s2 = "".join(["hel", "lo"])print(s1 is s2) # False三、深拷贝与浅拷贝
3.1 拷贝方式对比
import copy
original = [[1, 2, 3], [4, 5, 6]]
# 1. 赋值:共享引用assign = originalprint(assign is original) # True
# 2. 浅拷贝:只拷贝第一层shallow = copy.copy(original)print(shallow is original) # Falseprint(shallow[0] is original[0]) # True - 内部对象共享
# 3. 深拷贝:递归拷贝所有层级deep = copy.deepcopy(original)print(deep is original) # Falseprint(deep[0] is original[0]) # False - 完全独立3.2 拷贝操作示例
# 列表拷贝的几种方式lst = [1, 2, 3]
# 切片拷贝lst_copy1 = lst[:]
# list() 拷贝lst_copy2 = list(lst)
# copy() 方法lst_copy3 = lst.copy()
# 字典拷贝d = {"a": 1, "b": [1, 2]}d_shallow = d.copy() # 浅拷贝d_deep = copy.deepcopy(d) # 深拷贝
# 列表推导式lst_copy = [x for x in lst]
# 列表生成器gen = (x for x in range(10)) # 生成器,非拷贝3.3 常见陷阱
# 陷阱1:可变默认值参数def append_to(element, target=[]): # 危险! target.append(element) return target
print(append_to(1)) # [1]print(append_to(2)) # [1, 2] - 不是 [2]!
# 正确做法def append_to_fixed(element, target=None): if target is None: target = [] target.append(element) return target
# 陷阱2:循环引用class Node: def __init__(self, value): self.value = value self.next = None
a = Node(1)b = Node(2)a.next = b # a -> bb.next = a # b -> a (循环引用)
# deepcopy 可以处理循环引用import copya_copy = copy.deepcopy(a) # 正常工作四、命名空间与作用域
4.1 LEGB 规则
Python 遵循 LEGB 规则查找变量:
L - Local(局部作用域)E - Enclosing(闭包作用域)G - Global(全局作用域)B - Built-in(内置作用域)x = "global"
def outer(): x = "enclosing"
def inner(): x = "local" print(x) # "local"
inner() print(x) # "enclosing"
outer()print(x) # "global"4.2 global 与 nonlocal
# global:修改全局变量counter = 0
def increment(): global counter counter += 1
# nonlocal:修改外层(非全局)变量def outer(): count = 0
def inner(): nonlocal count count += 1
inner() print(count) # 1
# 常见错误def bad_counter(): count = 0 def increment(): count = count + 1 # 错误!会创建新的局部变量 increment()4.3 闭包与延迟绑定
# 闭包:内部函数记住外层变量def make_multiplier(factor): def multiplier(number): return number * factor return multiplier
times3 = make_multiplier(3)times5 = make_multiplier(5)print(times3(10)) # 30print(times5(10)) # 50
# 陷阱:延迟绑定def create_funcs(): funcs = [] for i in range(3): funcs.append(lambda: i) # 所有函数返回相同的 i return funcs
f1, f2, f3 = create_funcs()print(f1()) # 2 (不是 0)print(f2()) # 2 (不是 1)print(f3()) # 2
# 正确做法:使用默认参数捕获值def create_funcs_fixed(): funcs = [] for i in range(3): funcs.append(lambda i=i: i) # i=i 捕获当前值 return funcs五、Python 版本差异(3.8-3.12)
5.1 主要版本特性
| 版本 | 特性 |
|---|---|
| 3.8 | 赋值表达式 :=、位置参数 |
| 3.9 | 字典合并 |、类型提示泛型 |
| 3.10 | match-case、结构化模式匹配 |
| 3.11 | 异常组 except*、TaskGroup |
| 3.12 | 更友好的错误信息、增量解析 |
5.2 新语法示例
# Python 3.8: 赋值表达式if (n := len(data)) > 10: print(f"List has {n} elements")
# Python 3.9: 字典合并d1 = {"a": 1, "b": 2}d2 = {"b": 3, "c": 4}print(d1 | d2) # {"a": 1, "b": 3, "c": 4}
# Python 3.10: match-casedef http_status(status): match status: case 200: return "OK" case 404: return "Not Found" case _: return "Unknown"
# Python 3.10: 结构化模式匹配def get_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})"支持与分享
如果这篇文章对你有帮助,欢迎支持作者或分享给更多人
Python 基础语法与核心概念
https://blog.souloss.com/posts/interview/python-basics/ 部分信息可能已经过时
相关文章 智能推荐
1
Python 函数与高级特性
面试 Python 函数高级特性——装饰器原理、生成器与迭代器协议、上下文管理器、偏函数与可调用对象。
2
Python 并发与异步编程
面试 Python 并发编程——GIL 机制、asyncio 异步编程、threading 多线程、multiprocessing 多进程、协程与生成器。
3
Kubernetes 安全与 RBAC
面试 Kubernetes 安全——RBAC 权限模型、Security Context、Pod Security Standards、网络策略、Secret 管理。
4
Python 面向对象与设计模式
面试 Python 面向对象编程——类变量与实例变量、继承与 MRO、常见设计模式、单例模式实现。
5
Kubernetes 核心架构与组件
面试 Kubernetes 核心架构——Control Plane 组件、Node 组件、Pod 生命周期、Deployment 管理。






