Python 的 Slots优化

等级 5349 次按键

这展示了__slots__用于内存优化。使用slots的类通过避免创建实例__dict__来减少内存使用。

Python 代码

# RegularPoint是普通类
# 有__dict__用于动态存储属性
1class RegularPoint:
# __init__设置x和y坐标
# 在实例的__dict__中创建条目
2 def __init__(self, x: int, y: int):
3 self.x = x
4 self.y = y
5
# SlottedPoint使用__slots__进行优化
# 不创建__dict__,节省内存
6class SlottedPoint:
# __slots__定义固定的属性集
# 实例只能存储x和y
7 __slots__ = ("x", "y")
8
# __init__设置与RegularPoint相同的属性
# 但存储在slots而不是__dict__中
9 def __init__(self, x: int, y: int):
10 self.x = x
11 self.y = y
12
# 导入sys用于内存大小检查
13import sys
# 创建普通类的实例
14regular = RegularPoint(1, 2)
# 创建使用slots的类的实例
15slotted = SlottedPoint(1, 2)
16
# 显示普通实例的__dict__大小
# __dict__为属性存储占用额外内存
17print(f"Regular: {sys.getsizeof(regular.__dict__)} bytes dict")
# 使用slots的实例没有__dict__
# 属性直接存储在slots中
18print(f"Slotted has no __dict__")

运行结果

Regular: 64 bytes dict
Slotted has no __dict__
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • _× 20
  • :× 9
  • "× 8
  • (× 8
  • )× 8
  • ,× 7
  • =× 7
  • .× 6
  • {× 1
  • }× 1

Python 等级 5 的更多代码示例

← 返回 Python 打字练习