Python diagram itself traversal and weak reference use

Source: Internet
Author: User
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 () ~

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.