python 图 自身遍历及弱引用使用

在【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作为图可能的节点,每次在next调用中均返回next节点

利用这个迭代器,就可以轻松打印出图的结构:

def __str__(self):

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

Graph:

one->two->three->one

实现一个图结构需要利用python里面的弱引用,

我们先看一下标准的向图结构中增加下一节点的代码:

def set_next(self, other):

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

       self.other = other

这样绑定后,在属性字段中,增加一个对于下一节点的引用

c.__dict__

{'other': <Graph at 0xb7507e4c name=2>, 'name': '1'}

所以,即使手动调用了 a = None, b = None, c = None,对象也不会被删除

Garbage:[<Graph at 0xb739856c name=one>,

<Graph at 0xb739866c name=two>,

<Graph at 0xb739868c name=three>,

{'name': 'one', 'other': <Graph at 0xb739866c name=two>},

{'name': 'two', 'other': <Graph at 0xb739868c name=three>},

{'name': 'three', 'other': <Graph at 0xb739856c name=one>}]

而弱引用是指“引用一个对象,但并不增加被引用对象的指针计数”

可以通过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对象~

  • 初学者学习python2还是python3?
  • python获取本机IP、mac地址、计算机名
  • 详解python2 和 python3的区别
  • python基础之删除文件及删除目录的方法
  • 用python求第1000个质数的值
  • python常用函数年初大总结
  • Python3 - 时间处理与定时任务
  • Python开发的CMS系统,Silva CMS 3 发布
  • python基础之使用os.system来执行系统命令
  • 判断python字典中key是否存在的两种方法
  • 初学者学习python2还是python3?
  • python基础之删除文件及删除目录的方法
  • python获取本机IP、mac地址、计算机名
  • python获取系统时间(时间函数详解)
  • 详解python2 和 python3的区别
  • 用python求第1000个质数的值
  • Python3 - 时间处理与定时任务
  • 命令行看糗百
  • Python算法之---冒泡,选择,插入排序算法
  • python 中求和函数 sum详解
  • range方法在Python2和Python3中的不同
  • python3 数组(列表)初始化
  • 记一次crontab中date命令错用导致的问题
  • MySQL用LIKE特殊字符搜索
  • CentOS 7 下修改主机名
  • Python3正则表达式之:(?(id/name)y...
  • TIOBE编程语言排行榜2019年 Python稳居前三
  • 解压命令unzip常用方法汇总
  • 解析redis备份文件rdb的两种方法及对比
  • 百度视觉语义化平台2.0:交互升级和...
  • 5G时代的视觉语义化技术:软硬结合...
  • 百度AutoDL重磅升级至3.0:设计、迁...