mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
300 字
1 分钟
Python 基础语法与核心概念
2023-11-03

一、基本数据类型#

1.1 数据类型一览#

类型示例可变否说明
int42, 0b101, 0xFF任意精度整数
float3.14, 1e10双精度浮点
complex3+4j复数
str"hello", 'world'Unicode 字符串
bytesb'\xff\x00'字节序列
boolTrue, FalseTrue=1, False=0
list[1, 2, 3]动态数组
tuple(1, 2, 3)不可变序列
dict{"a": 1}哈希表
set{1, 2, 3}无序集合
frozensetfrozenset({1,2})不可变集合

1.2 数值类型细节#

# 整数缓存机制(-5 到 256)
a = 256
b = 256
print(a is b) # True - 缓存范围内
a = 257
b = 257
print(a is b) # False - 超出缓存范围
# 进制表示
hex_val = 0xFF # 十六进制 -> 255
bin_val = 0b1010 # 二进制 -> 10
oct_val = 0o17 # 八进制 -> 15
# 下划线分隔符(Python 3.6+)
million = 1_000_000
version = 3_.11_._version
# 复数
c = 3 + 4j
print(c.real) # 3.0
print(c.imag) # 4.0
print(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 = 30
print(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 = None
b = None
print(a is b) # True - None 是单例

2.2 整数缓存机制#

# Python 整数缓存范围:-5 到 256
# 这是 CPython 的实现细节,其他实现可能不同
# 缓存范围内的整数
x = 256
y = 256
print(x is y) # True
# 超出缓存范围
x = 257
y = 257
print(x is y) # False
# 编译时常量
x = 1000
y = 500 + 500 # 编译时计算结果
print(x is y) # 可能为 True(Python 优化)
x = 1000
y = 500
z = x + 0
print(x is z) # 可能为 False

2.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 = original
print(assign is original) # True
# 2. 浅拷贝:只拷贝第一层
shallow = copy.copy(original)
print(shallow is original) # False
print(shallow[0] is original[0]) # True - 内部对象共享
# 3. 深拷贝:递归拷贝所有层级
deep = copy.deepcopy(original)
print(deep is original) # False
print(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 -> b
b.next = a # b -> a (循环引用)
# deepcopy 可以处理循环引用
import copy
a_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)) # 30
print(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.10match-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-case
def 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/
作者
Souloss
发布于
2023-11-03
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时