>[success] # 使用slots节省对象内存优化 ~~~ 1.普通创建一个类的时候,属性都会被装在__dict__ 方法中 2.使用__slots__ 中列出的属性名在内部被映射到这个数组的指定小标上。使用slots一个不好的地方就是我们不能再给实例添加 新的属性了,只能使用在 __slots__ 中定义的那些属性名 3.该类无法被继承 ~~~ >[danger] ##### 简单使用dict ~~~ 1.当对象调用的时候返回的是属性键值对字典 ~~~ ~~~ class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day d = Date("1","1","1") for k,v in d.__dict__.items(): print(k,v) 打印结果: year 1 month 1 day 1 ~~~ >[danger] ##### 使用内存优化方案 ~~~ 1.使用__slots__ 保存属性后类就没有了dict 方法 ~~~ ~~~ class Date: __slots__ = ['year', 'month', 'day'] def __init__(self, year, month, day): self.year = year self.month = month self.day = day d = Date("1","1","1") for k,v in d.__dict__.items(): print(k,v) 打印结果 Traceback (most recent call last): File "D:/day4/test.py", line 12, in <module> for k,v in d.__dict__.items(): AttributeError: 'Date' object has no attribute '__dict__' ~~~