2025-09-10:仓库迁移
This commit is contained in:
11
8.类与对象/4.创建大量实例时如何节省内存.py
Normal file
11
8.类与对象/4.创建大量实例时如何节省内存.py
Normal file
@@ -0,0 +1,11 @@
|
||||
# 如果你需要创建大量的实例,那么你可以在类的定义中增加__slots__属性来让类不创建__dict__字典
|
||||
|
||||
class Date:
|
||||
__slots__ = ('year', 'month', 'day')
|
||||
def __init__(self, year, month, day):
|
||||
self.year = year
|
||||
self.month = month
|
||||
self.day = day
|
||||
|
||||
# 这会让类围绕着__slots__属性进行构建,副作用就是这个类被写死了,我们无法为它的实例添加新的属性
|
||||
# 使用了__slots__的类会失去多重继承的用法,请确保只在被当作数据结构的类中使用该方法
|
Reference in New Issue
Block a user