看python社區(qū)大媽組織的內(nèi)容里邊有一篇講python內(nèi)存優(yōu)化的,用到了__slots__。然后查了一下,總結(jié)一下。感覺(jué)非常有用
python類在進(jìn)行實(shí)例化的時(shí)候,會(huì)有一個(gè)__dict__屬性,里邊有可用的實(shí)例屬性名和值。聲明__slots__后,實(shí)例就只會(huì)含有__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 # 這個(gè)是不成功的 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
新聞熱點(diǎn)
疑難解答
圖片精選