2014-11-25 54 views
1

我有一個簡單的類,它的一個實例可以接受輸入值並提供輸出值。我想創建這個類的實例的網絡,其中一些實例的輸出鏈接到其他實例的輸入。有沒有一種類或其他方式來以清晰,高效的方式定義這樣一個網絡?如何在Python中創建類的實例的網絡

回答

1

你需要的是實現一個directed graph。有很多方法來實現圖我建議你閱讀Python Patterns - Implementing Graphs

一個簡單的想法:你可以持有你想要傳遞輸入的每個實例的列表(這也是一個圖)。

class Node: 

    def __init__(self): 
     self.targets = [] 

    def output(self): 
     for target in self.targets: 
      target.process_input(self.produce_output()) 


    def process_input(self, input): 
     # Process some data here. 
     pass 


    def produce_output(): 
     # Produce some data here. 
     pass