刘心向学(30)深入理解 Python 中的__slots__

B站影视 韩国电影 2025-06-01 08:50 1

摘要:在 Python 面向对象编程中,类实例默认使用一个字典(__dict__)来存储其所有属性。这种方式非常灵活,但也带来了额外的内存开销和访问效率问题。Python 提供了一个特殊的类属性__slots__,用于显式声明类实例的属性集合,从而优化内存使用并提升

分享兴趣,传播快乐,

增长见闻,留下美好!

亲爱的您,这里是LearningYard新学苑。

今天小编为大家带来文章 “刘心向学(30)深入理解 Python 中的__slots__”

欢迎您的访问。

Share interest, spread happiness,

Increase knowledge, leave a beautiful!

Dear, this is LearningYard Academy.

Today, the editor brings you an article. “Liu Xinxiang (30):In-Depth Understanding of __slots__ in Python”

Welcome to your visit.

一、思维导图(Mind Map)

二、引言(Introduction)

在 Python 面向对象编程中,类实例默认使用一个字典(__dict__)来存储其所有属性。这种方式非常灵活,但也带来了额外的内存开销和访问效率问题。Python 提供了一个特殊的类属性__slots__,用于显式声明类实例的属性集合,从而优化内存使用并提升访问速度。

In Python's object-oriented programming, class instances by default use a dictionary (__dict__) to store all their attributes. This approach is very flexible but also brings additional memory overhead and slower attribute access. Python provides a special class attribute __slots__ to explicitly declare the set of allowed attributes for an instance, thereby optimizing memory usage and improving access speed.

三、什么是__slots__?(What is __slots__)

__slots__是一个类级别的变量,用于限制该类实例允许拥有的属性,并告诉解释器不要为每个实例创建__dict__和__weakref__属性。

__slots__ is a class-level variable used to restrict the allowed attributes of a class instance, and it tells the interpreter not to create a __dict__ or __weakref__ for each instance.

The basic syntax is as follows:

在这个例子中,Person类的每个实例只能拥有name和age两个属性。

In this example, each instance of the Person class can only have two attributes: name and age.

四、__slots__的优势(Advantages of __slots__)

1. 减少内存占用(Reduces Memory Usage)

使用__slots__后,Python 不再为每个实例分配一个字典,而是使用更紧凑的结构(通常是数组)来存储属性。这对于大量创建对象的程序来说,可以显著降低内存消耗。

After using __slots__, Python no longer allocates a dictionary for each instance. Instead, it uses a more compact structure (usually an array) to store attributes. For programs that create a large number of objects, this can significantly reduce memory consumption.

2. 提高访问速度(Improves Access Speed)

相比字典查找,通过固定偏移量访问属性更快,因此属性读写的速度也会有所提升。

Accessing attributes via fixed offsets is faster than dictionary lookups, so the speed of reading and writing attributes improves.

3. 防止随意添加属性(Prevents Accidental Attribute Addition)

如果你希望限制类的接口或避免运行时意外添加属性,使用__slots__可以强制开发者只使用定义好的属性。

If you want to restrict the interface of a class or prevent accidental addition of new attributes at runtime, using __slots__ forces developers to only use the predefined attributes.

五、__slots__的限制(Limitations of __slots__)

尽管__slots__有很多优点,但它也有一些局限性需要注意:

Although __slots__ offers many advantages, there are also some limitations to be aware of:

不能动态添加未在__slots__中定义的属性:

You cannot dynamically add attributes not defined in __slots__:

子类不会自动继承父类的__slots__:

Subclasses do not automatically inherit the parent’s __slots__:

如果父类使用了__slots__,子类也需要重新声明自己的__slots__,否则会创建__dict__。

If a parent class uses __slots__, subclasses must re-declare their own __slots__ unless they want to allow dynamic attributes.

无法使用 __weakref__(除非显式包含):默认情况下,使用__slots__的类不支持弱引用(weakref),这可能会影响某些框架或库的行为。

By default, classes using __slots__ do not support weak references (weakref), which may affect behavior in certain frameworks or libraries.

六、典型应用场景(Typical Use Cases)

1. 需要频繁创建大量对象的场景(Creating large numbers of objects frequently)

如游戏开发中的角色、粒子系统、数据分析中的记录等,使用__slots__能有效减少内存开销。

such as characters in game development, particles in a particle system, or records in data analysis — benefits from using __slots__ to reduce memory overhead.

2. 对性能要求较高的类(Classes with High Performance Requirements)

如果某个类的实例被频繁访问或修改属性,使用__slots__可以提升访问效率。

For classes whose instances are frequently accessed or modified ,using __slots__ can improve performance.

3. 封装良好的数据模型类(Well-Encapsulated Data Model Classes)

当你希望明确指定类的属性结构,并防止误操作添加新属性时,__slots__是一个很好的选择。

When you want to explicitly define the structure of a class and prevent accidental addition of attributes, __slots__ is a good choice.

七、高级用法(Advanced Usage)

1. 继承中使用__slots__(Using __slots__in inheritance)

如果基类有__slots__,子类也可以继续使用:

If the base class has __slots__, the subclass can also continue to use it:

这样,Dog实例只会存储name和breed,没有__dict_。

This way, Dog instances will only store name and breed, without a __dict__.

2. 允许动态添加属性(保留__dict__)Allowing Dynamic Attribute Addition (Preserving __dict__)

如果你既想使用__slots__提升部分属性的访问效率,又想保留动态添加其他属性的能力,可以在__slots__中省略某些字段,或者显式加入 '__dict__':

If you want to use __slots__ to improve access speed for some attributes while still allowing others to be added dynamically, you can omit certain fields from __slots__ or explicitly include '__dict__':

八、性能对比示例(Performance Comparison Example)

我们来做一个简单的测试,比较使用和不使用__slots__在内存占用上的差异:

Let’s do a simple test comparing memory usage with and without __slots__:

输出结果大致如下(具体数值因平台而异):

The output might look like this (exact values vary per platform):

NormalClass 占用内存: 4500 KB

SlottedClass 占用内存: 700 KB

可以看出,使用__slots__后内存占用明显下降。

As shown, using __slots__ significantly reduces memory usage.

九、结语(Conclusion)

__slots__是 Python 提供的一个强大但常被忽视的功能。它不仅能够帮助我们编写更高效、更节省资源的代码,还能增强类的设计严谨性。当你面对需要创建大量对象、关注性能或希望严格控制属性结构的场景时,不妨考虑使用__slots__来优化你的代码。

__slots__ is a powerful yet often overlooked feature in Python. It helps us write more efficient and resource-friendly code, while also enforcing stricter class design. When dealing with scenarios involving frequent object creation, performance concerns, or strict control over attribute structure, consider using __slots__ to optimize your code.

今天的分享就到这里了。

如果您对文章有独特的想法,

欢迎给我们留言,

让我们相约明天。

祝您今天过得开心快乐!

That's all for today's sharing.

If you have a unique idea about the article,

please leave us a message,

and let us meet tomorrow.

I wish you a nice day!

参考资料:通义千问

参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.

Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.

本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通! LearningYard新学苑

文字:song

排版:song

审核|hyz

来源:LearningYard学苑

相关推荐