新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Python中__slots__的禁用實例
1、說明

python 的對象屬性值都是采用字典存儲的,當(dāng)我們處理數(shù)成千上萬甚至更多的實例時,內(nèi)存消耗可能是一個問題,因為字典哈希表的實現(xiàn),總是為每個實例創(chuàng)建了大量的內(nèi)存。所以 Python 提供了一種 ____slots____ 的方式來禁用實例使用 __dict__,以優(yōu)化此問題。
2、實例
通過 __slots__ 來指定屬性后,會將屬性的存儲從實例的 __dict__ 改為類的 __dict__ 中:
class Test:
__slots__ = ('a', 'b')
def __init__(self, a, b):
self.a = a
self.b = b
>>> t = Test(1, 2)
>>> t.__dict__
AttributeError: 'Test' object has no attribute '__dict__'
>>> Test.__dict__
mappingproxy({'__module__': '__main__',
'__slots__': ('a', 'b'),
'__init__': ,
'a': ,
'b': ,
'__doc__': None}) 以上就是Python中__slots__的禁用實例,希望對大家有所幫助。更多Python學(xué)習(xí)推薦:python教學(xué)
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
當(dāng)前標(biāo)題:創(chuàng)新互聯(lián)Python教程:Python中__slots__的禁用實例
文章起源:http://fisionsoft.com.cn/article/cdoecgh.html


咨詢
建站咨詢
