VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python3标准库:pickle对象串行化(3)

def preorder_traversal(root, seen=None, parent=None):
  • """Generator function to yield the edges in a graph.
  • """
  • if seen is None:
  • seen = set()
  • yield (parent, root)
  • if root in seen:
  • return
  • seen.add(root)
  • for node in root:
  • recurse = preorder_traversal(node, seen, root)
  • for parent, subnode in recurse:
  • yield (parent, subnode)
  •  
  • def show_edges(root):
  • "Print all the edges in the graph."
  • for parent, child in preorder_traversal(root):
  • if not parent:
  • continue
  • print('{:>5} -> {:>2} ({})'.format(
  • parent.name, child.name, id(child)))
  •  
  • # Set up the nodes.
  • root = Node('root')
  • a = Node('a')
  • b = Node('b')
  • c = Node('c')
  •  
  • # Add edges between them.
  • root.add_edge(a)
  • root.add_edge(b)
  • a.add_edge(b)
  • b.add_edge(a)
  • b.add_edge(c)
  • a.add_edge(a)
  •  
  • print('ORIGINAL GRAPH:')
  • show_edges(root)
  •  
  • # Pickle and unpickle the graph to create
  • # a new set of nodes.
  • dumped = pickle.dumps(root)
  • reloaded = pickle.loads(dumped)
  •  
  • print('\nRELOADED GRAPH:')
  • show_edges(reloaded)
  • 重新加载的节点并不是同一个对象,但保持了节点之间的关系,而且如果对象有多个引用,那么只会重新加载这个对象的一个副本。要验证这两点,可以在通过pickle传递节点之前和之后检查节点的id()值。

    
    相关教程
    关于我们--广告服务--免责声明--本站帮助-友情链接--版权声明--联系我们       黑ICP备07002182号