Home  >  Article  >  Backend Development  >  Python graph self traversal and use of weak references

Python graph self traversal and use of weak references

高洛峰
高洛峰Original
2016-10-19 16:43:321295browse

A piece of code I saw in [python standard library] is very helpful:

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


The two yields at the beginning and end are only returned once, as the starting point and end point of the cycle graph, and n is the graph Possible nodes, the next node is returned every time in the next call

Using this iterator, you can easily print out the structure of the graph:

def __str__(self):

Return '->'.join((n .name for n in self.all_nodes()))


Graph:

one->two->three->one


To implement a graph structure, you need to use weak references in python,

Let's first look at the standard code for adding the next node to the graph structure:

def set_next(self, other):

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

                                       other = other


After binding like this, add a reference to the next node in the attribute field

c.__dict__

{'other': , 'name': '1'}


So, even if a = None, b = None, c = None are called manually, the object will not be deleted

Garbage: [,

,

,

{'name': ' one', 'other': },

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

{'name': 'three', 'other': }]

and weak Reference means "referring to an object, but does not increase the pointer count of the referenced object"

You can use c = weekref.ref(k,func)

to specify the referenced object and the action after object deletion func

call When, use c() to reference k

But in the previous example, we need a "proxy object" to proxy the referenced object, so that the set_next function can be used for the variable other like a normal variable

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

​​


Thus avoiding referencing an other object through other()~


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:python global variablesNext article:python global variables