新聞中心
在python中有許多以__開頭的變量,這些變量是什么意思呢?這里介紹下[__dir__, __slots__, __weakref__,__missing__, __contains__]

__dir__ -> 看個(gè)小例子就知道了
In [1]: class T(object): ...: pass ...: In [2]: t = T() In [3]: t.
啥也沒有...
In [4]: class T2(object): ...: def __dir__(self): ...: return ['a', 'b'] ...: In [5]: t = T2() In [6]: t. t.a t.b In [7]: dir(t) Out[7]: ['a', 'b']
看出來(lái)了把, 不解釋, 但是這個(gè)__dir__是相對(duì)于類的實(shí)例有效果的.
__slots__
這個(gè)在我初學(xué)python的時(shí)候就被模糊了, 原來(lái)的理解是它的出現(xiàn)替代了__dict__,也就是說你只能給__slots__ 這個(gè)變量列表項(xiàng)的屬性賦值. 對(duì)外的接口減少了,也安全了. 后來(lái)看了這篇Saving 9 GB of RAM with Python’s slots. 好久不做運(yùn)維了,在生產(chǎn)環(huán)境究竟怎么樣我無(wú)法定論, 也提到了,在對(duì)象實(shí)例很多的時(shí)候他能幫助減少內(nèi)存, 詳見https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch08s04.html. 這里來(lái)個(gè)小實(shí)驗(yàn)(在Hacker News也被討論過https://news.ycombinator.com/item?id=6750187)
代碼例子(我對(duì)細(xì)節(jié)做注釋):
# coding=utf-8
import sys
from itertools import starmap, product
class SlotTest(object):
# __slots__ = ['x', 'y', 'z'] 主要對(duì)比去掉這句和包含這句程序內(nèi)存占用
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return "{} {} {}".format(self.x, self.y, self.z)
p = product(range(10000), range(20), [4]) # 創(chuàng)建0-1000 & 0-20 & 4 的笛卡爾積
a = list(starmap(SlotTest, p)) # 相當(dāng)于對(duì)每個(gè)SlotTest實(shí)例化,實(shí)例化的格式是p的長(zhǎng)度
print a[0]
sys.stdin.read(1)結(jié)果對(duì)比:
$pmap -x `ps -ef|grep test_slot.py|grep -v grep|awk '{print $2}'`|grep total # 未使用__slots__
total kB 103496 76480 73728
$pmap -x `ps -ef|grep test_slot.py|grep -v grep|awk '{print $2}'`|grep total # 使用了__slots__
total kB 49960 22888 20136結(jié)果很明顯,內(nèi)存占用減少了很多...
__weakref__ 弱引用
首先先說下weakref: 弱引用,與強(qiáng)引用相對(duì),是指不能確保其引用的對(duì)象不會(huì)被垃圾回收器回收的引用。一個(gè)對(duì)象若只被弱引用所引用,則被認(rèn)為是不可訪問(或弱可訪問)的,并因此可能在任何時(shí)刻被回收. 在Python中,當(dāng)一個(gè)對(duì)象的引用數(shù)目為0的時(shí)候,才會(huì)被從內(nèi)存中回收. 但是被循環(huán)引用呢?
In [1]: import weakref In [2]: import gc In [3]: class Obj(object): ...: def a(self): ...: return 1 ...: In [4]: obj = Obj() In [5]: s = obj In [6]: gc.collect() # 不可達(dá)引用對(duì)象的數(shù)量 Out[6]: 3 In [7]: print s is obj True In [8]: obj = 1 # 最初的被引用的對(duì)象改變了. In [9]: gc.collect() Out[9]: 0 In [10]: s is None # s還是指向了Obj 引用計(jì)數(shù)為1 Out[10]: False In [11]: s Out[11]: <__main__.Obj at 0x2b36510> ----華麗的分割一下 In [12]: obj = Obj() In [13]: r = weakref.ref(obj) # 讓obj變成那個(gè)弱引用 In [14]: gc.collect() Out[14]: 211 In [15]: r() is obj True In [16]: obj = 1 In [17]: gc.collect() Out[17]: 0 In [18]: r() is None # 弱引用計(jì)數(shù)器沒有增加,所以當(dāng)obj不在引用Obj的時(shí)候,Obj對(duì)象就被釋放了 Out[18]: True
好吧, 我的總結(jié)是弱引用是個(gè)好東西, 但是加了__slots__就不支持弱引用了. 所以需要__weakref__
In [9]: class T3(object): ...: __slots__ = [] ...: In [10]: class T4(object): ....: __slots__ = '__weakref__' # 這樣就支持了weakref ....: In [11]: import weakref In [12]: t3 = T3() In [13]: t4 = T4() In [14]: weakref.ref(t3) --------------------------------------------------------------------------- TypeError Traceback (most recent call last)in () ----> 1 weakref.ref(t3) TypeError: cannot create weak reference to 'T3' object In [15]: weakref.ref(t4) Out[15]:
__contains__ 判斷某值 in/not in 實(shí)例
In [1]: class NewList(object): ...: def __init(self, values): ...: self.values = values ...: def __contains__(self, value): ...: return value in self.values ...: In [2]: l = NewList([1, 2, 3, 4]) In [3]: 4 in l Out[3]: True In [4]: 10 in l Out[4]: False __missing__
最初看這個(gè)特殊方法是看python標(biāo)準(zhǔn)庫(kù)的源碼的時(shí)候(collections#L421):
class Counter(dict): ... def __missing__(self, key): 'The count of elements not in the Counter is zero.' # Needed so that self[missing_item] does not raise KeyError return 0
什么意思呢?
In [6]: c = collections.Counter({'a':1})
In [7]: c['b'] # 沒有鍵的count設(shè)置默認(rèn)值0
Out[7]: 0 網(wǎng)站標(biāo)題:創(chuàng)新互聯(lián)Python教程:python幾個(gè)__開頭的方法解釋
分享鏈接:http://m.fisionsoft.com.cn/article/dhsogie.html


咨詢
建站咨詢
