看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
新聞熱點
疑難解答