每个实例包含一个字典,slot 让实例变成tup 或List,减少内存,但不能再增加属性
For classes that primarily serve as simple data structures,you can often greatly reduce the memory footprint of instances by adding the slots attribute to the class defi‐ nition. For example:
class Date:
slots = [‘year‘,‘month‘,‘day‘] def init(self,year,month,day):
self.year = year self.month = month self.day = day
When you define slots,Python uses a much more compact internal representation for instances. Instead of each instance consisting of a dictionary,instances are built around a small fixed-sized array,much like a tuple or List. Attribute names Listed in the slots specifIEr are internally mapped to specific indices within this array. A sIDe effect of using slots is that it is no longer possible to add new attributes to instances— you are restricted to only those attribute names Listed in the slots specifIEr
总结以上是内存溢出为你收集整理的python slot全部内容,希望文章能够帮你解决python slot所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)