99热99这里只有精品6国产,亚洲中文字幕在线天天更新,在线观看亚洲精品国产福利片 ,久久久久综合网

歡迎加入QQ討論群258996829
麥子學院 頭像
蘋果6袋
6
麥子學院

Python中__開頭的幾個方法詳解

發(fā)布時間:2016-11-29 17:42  回復:0  查看:2709   最后回復:2016-11-29 17:42  

今天和大家分享的主要是python開發(fā)中常用的幾個__開頭的方法,希望可以幫助大家更好的學習python ,一起來看看吧。

   今天我來說3個他沒有提到的[__dir__, __slots__, __weakref__], 再強調下他提到的2個[__missing__, __contains__]

  __dir__ -> 看個小例子就知道了

  In [1]:classT(object):

  ...: pass

  ...:In [2]: t = T()In [3]: t.

  啥也沒有...

  In [4]:classT2(object):

  ...: def__dir__(self):

  ...: return['a','b']

  ...:In [5]: t = T2()In [6]: t.

  t.a t.bIn [7]: dir(t)Out[7]: ['a','b']

  看出來了把, 不解釋, 但是這個__dir__是相對于類的實例有效果的.

  __slots__

  這個在我初學python的時候就被模糊了, 原來的理解是它的出現(xiàn)替代了__dict__,也就是說你只能給__slots__

  這個變量列表項的屬性賦值. 對外的接口減少了,也安全了.

  代碼例子(我對細節(jié)做注釋):

  # coding=utf-8

  importsys

  fromitertoolsimportstarmap, product

  classSlotTest(object):# __slots__ = ['x', 'y', 'z'] 主要對比去掉這句和包含這句程序內存占用

  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)) # 相當于對每個SlotTest實例化,實例化的格式是p的長度

  printa[0]

  sys.stdin.read(1)

  結果對比:

  $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

  結果很明顯,內存占用減少了很多…

  __weakref__ 弱引用

  首先先說下 weakref : 弱引用,與強引用相對,是指不能確保其引用的對象不會被垃圾回收器回收的引用。一個對象若只被弱引用所引用,則被認為是不可訪問(或弱可訪問)的,并因此可能在任何時刻被回收.

  在Python中,當一個對象的引用數(shù)目為0的時候,才會被從內存中回收. 但是被循環(huán)引用呢?

  In [1]:importweakref

  In [2]:importgc

  In [3]:classObj(object):

  ...: defa(self):

  ...: return1

  ...:In [4]: obj = Obj()

  In [5]: s = obj

  In [6]: gc.collect()# 不可達引用對象的數(shù)量

  Out[6]:3

  In [7]:printsisobjTrue

  In [8]: obj =1# 最初的被引用的對象改變了.

  In [9]: gc.collect()

  Out[9]:0

  In [10]: sisNone# s還是指向了Obj 引用計數(shù)為1

  Out[10]:False

  In [11]: s

  Out[11]:<__main__.obj at0x2b36510="">

  ----華麗的分割一下

  In [12]: obj = Obj()

  In [13]: r = weakref.ref(obj)# 讓obj變成那個弱引用

  In [14]: gc.collect()

  Out[14]:211

  In [15]: r()isobjTrue

  In [16]: obj =1

  In [17]: gc.collect()

  Out[17]:0

  In [18]: r()isNone# 弱引用計數(shù)器沒有增加,所以當obj不在引用Obj的時候,Obj對象就被釋放了

  Out[18]:True

  好吧, 我的總結是弱引用是個好東西, 但是加了__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]:<weakref at 0x2766f70; to 'T4' at 0x2586fd8>

  __contains__ 判斷某值 in/not in 實例

  In [1]:classNewList(object):

  ...: def__init(self, values):

  ...: self.values = values

  ...: def__contains__(self, value):

  ...: returnvalueinself.values

  ...:In [2]: l = NewList([1,2,3,4])

  In [3]:4inlOut[3]:True

  In [4]:10inlOut[4]:False

  __missing__

  最初看這個特殊方法是看python標準庫的源碼的時候(collections#L421):

  classCounter(dict):

  ...

  def__missing__(self, key):'The count of elements not in the Counter is zero.'# Needed so that self[missing_item] does not raise KeyErrorreturn0

  什么意思呢?

  In [6]: c = collections.Counter({'a':1})

  In [7]: c['b']# 沒有鍵的count設置默認值0Out[7]:0

文章來源:小明明's à domicile

您還未登錄,請先登錄

熱門帖子

最新帖子

?