看python社區大媽組織的內容里邊有一篇講python內存優化的,用到了__slots__。然后查了一下,總結一下。感覺非常有用
python類在進行實例化的時候,會有一個__dict__屬性,里邊有可用的實例屬性名和值。聲明__slots__后,實例就只會含有__slots__里有的屬性名。
# coding: utf-8 class A(object): x = 1 def __init__(self): self.y = 2 a = A() print a.__dict__ print(a.x, a.y) a.x = 10 a.y = 10 print(a.x, a.y) class B(object): __slots__ = ('x', 'y') x = 1 z = 2 def __init__(self): self.y = 3 # self.m = 5 # 這個是不成功的 b = B() # print(b.__dict__) print(b.x, b.z, b.y) # b.x = 10 # b.z = 10 b.y = 10 print(b.y) class C(object): __slots__ = ('x', 'z') x = 1 def __setattr__(self, name, val): if name in C.__slots__: object.__setattr__(self, name, val) def __getattr__(self, name): return "Value of %s" % name c = C() print(c.__dict__) print(c.x) print(c.y) # c.x = 10 c.z = 10 c.y = 10 print(c.z, c.y) c.z = 100 print(c.z)
{'y': 2} (1, 2) (10, 10) (1, 2, 3) 10 Value of __dict__ 1 Value of y (10, 'Value of y') 100
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
