首頁  >  文章  >  後端開發  >  python 圖 自身遍歷及弱引用使用

python 圖 自身遍歷及弱引用使用

高洛峰
高洛峰原創
2016-10-19 16:43:321298瀏覽

在【python 標準函式庫】中看到的一段程式碼,非常有幫助:

def all_nodes(self):
        yield self
        n = self.other
        while n and n.name != self.name:
            yield n
            n = n.other
        if n is self:
            yield n
        return

   


首尾的2處yield都只回傳一次,作為循環圖的起點、終點,而n

首尾的2處yield都只回傳一次,作為循環圖的起點、終點可能的節點,每次在next調用中均返回next節點

利用這個迭代器,就可以輕鬆打印出圖的結構:

def __str__(self):

       return '->'.


       return '->'.

       return '->'.

   .name for n in self.all_nodes()))


Graph:

one->two->three->one

讓我們先來看看標準的在圖結構中增加下一節點的程式碼:

def set_next(self, other):


       print '%s.next %r' % ( self.name, other)

 other = other

這樣綁定後,在屬性字段中,增加一個對於下一節點的引用

c.__dict__


{'other':

, 'name': '1'}

所以,即使手動調用了a = None, b = None, c = None,物件也不會被刪除

Garbage:[

,

,

: ' one', 'other':

},

{'name': 'two', 'other':

},

{'name': 'three', 'other':

}]

而弱引用是指「引用一個對象,但不增加被引用對象的指針計數」

可以透過c = weekref.ref(k,func)  

來指定引用的對象及對象刪除後的動作func

調用時,使用c() 來引用k

但是在上個例子裡面,我們需要一個「代理對象」來代理這個被引用的對象,從而使set_next 函數對於變量other可以同正常變量一樣使用

def set_next(self, other):
        if other is not None:
            if self in other.all_nodes():
                other = weakref.proxy(other)
        super(WeakGraph, self).set_next(other)
        return

   


從而避免了透過other()來引用一個other物件~


🎜
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn