Python中的__SLOTS__屬性使用樣本_python

來源:互聯網
上載者:User

看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 = 10a.y = 10print(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 = 10b.y = 10print(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 = 10c.z = 10c.y = 10print(c.z, c.y)c.z = 100print(c.z)

{'y': 2}(1, 2)(10, 10)(1, 2, 3)10Value of __dict__1Value of y(10, 'Value of y')100 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.