Python中的__SLOTS__屬性使用示例
更新時間:2015年02月18日 15:45:42 投稿:junjie
這篇文章主要介紹了Python中的__SLOTS__屬性使用示例,本文直接給出代碼示例,需要的朋友可以參考下
看python社區(qū)大媽組織的內(nèi)容里邊有一篇講python內(nèi)存優(yōu)化的,用到了__slots__。然后查了一下,總結(jié)一下。感覺非常有用
python類在進(jìn)行實例化的時候,會有一個__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
相關(guān)文章
python多線程+代理池爬取天天基金網(wǎng)、股票數(shù)據(jù)過程解析
這篇文章主要介紹了python多線程+代理池爬取天天基金網(wǎng)、股票數(shù)據(jù)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08分析Python中設(shè)計模式之Decorator裝飾器模式的要點
這篇文章主要介紹了Python中設(shè)計模式之Decorator裝飾器模式模式,文中詳細(xì)地講解了裝飾對象的相關(guān)加鎖問題,需要的朋友可以參考下2016-03-03