A piece of code that you see in the Python standard library is 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 2 yield is returned only once, as the starting point and end point of the circular graph, and n as the possible node of the graph, each return to the next node in the next call
With this iterator, you can easily print out the structure of the diagram:
def __str__ (self):
Return '--'. Join ((N.name for N in Self.all_nodes ()))
Graph:
One->two->three->one
Implementing a graph structure requires the use of weak references in Python,
Let's take a look at the code for adding the next node to the standard graph structure:
def set_next (self, Other):
print '%s.next%r '% (Self.name, other)
Self.other = Other
After this binding, in the attribute field, add a reference to the next node
c.__dict__
{' Other ': , ' name ': ' 1 '}
So, even if you manually call a = none, B = none, c = None, the object is not deleted
garbage:[ ,
,
,
{' name ': ' One ', ' Other ': },
{' name ': ' Both ', ' other ': },
{' name ': ' Three ', ' Other ': }]
A weak reference refers to "referencing an object, but not increasing the pointer count of the referenced object"
can be passed C = weekref.ref (K,func)
To specify the referenced object and the action func after the object is deleted
When invoked, use C () to refer to K
But in the last example, we need a "proxy object" to proxy the referenced object, so that the Set_next function can be used as a normal variable for the variable other.
def set_next (self, Other): If and is not None: If-other.all_nodes (): Other = Weakref.proxy (Other)
super (Weakgraph, self). Set_next (Other) return
This avoids referencing an other object through other () ~