python在類中使用__slot__屬性


在類中定義__slot__屬性來限制實例的屬性字段,在創建大量對象的場合可以減少內存占用。

創建大量對象是內存占用對比:

  1. 類中不使用__slot__
class MySlot:def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

@profile()
def main():
    myObj_list = list()
    for i in range(50000):
        myObj = MySlot(i, i, i)
        myObj_list.append(myObj)

執行結果:

Line # Mem usage Increment Line Contents
================================================
401 39.7 MiB 39.7 MiB @profile()
402 def main():
403 39.7 MiB 0.0 MiB myObj_list = list()
404 49.9 MiB 0.0 MiB for i in range(50000):
405 49.9 MiB 0.1 MiB myObj = MySlot(i, i, i)
406 49.9 MiB 0.4 MiB myObj_list.append(myObj)

占用內存約10M

 

  1. 類中使用__slot__
class MySlot:
    __slots__ = ('a', 'b', 'c')
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

@profile()
def main():
    myObj_list = list()
    for i in range(50000):
        myObj = MySlot(i, i, i)
        myObj_list.append(myObj)

執行結果:

Line # Mem usage Increment Line Contents
================================================
401 40.3 MiB 40.3 MiB @profile()
402 def main():
403 40.3 MiB 0.0 MiB myObj_list = list()
404 45.7 MiB 0.0 MiB for i in range(50000):
405 45.7 MiB 0.1 MiB myObj = MySlot(i, i, i)
406 45.7 MiB 0.3 MiB myObj_list.append(myObj)

占用內存約5M

 

  1. 說明

  __slot__限制了屬性值,添加__slot__元組之外的屬性會報錯!

  __slot__限制的是實例屬性的添加,不限制類屬性的添加!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM