2015-06-23 26 views
5

Sto giocando con i grafici e ho codificato un modulo di mixaggio per la creazione di grafici. Voglio avere alcuni costruttori alternativi. Questo è quello che ho:Costruttori alternativi in ​​Python

class Graph(GraphDegree, GraphDegreePlot, GraphGeneration, object): 
    def __init__(self): 
     self.nodes = set([]) 
     self.edges = {} 
    def get_nodes(self): 
     """ 
     get nodes in graph 
     """ 
     return self.nodes 
    def get_number_of_nodes(self): 
     """ 
     get number of nodes in the graph 
     """ 
     return len(self.nodes) 
    def get_edges(self): 
     """ 
     get edges in graph 
     """ 
     return self.edges 
    def get_heads_in_edges(self): 
     """ 
     get heads in edges present on the graph 
     """ 
     return self.edges.values() 
    def add_node(self, node): 
     """ 
     add new node to graph 
     """ 
     if node in self.get_nodes(): 
      raise ValueError('Duplicate Node') 
     else: 
      self.nodes.add(node) 
      self.edges[node] = [] 
    def add_connection(self, edge): 
     """ 
     adds edge to graph 
     """ 
     origin = edge.get_origin() 
     destination = edge.get_destination() 
     if origin not in self.get_nodes() or destination not in self.get_nodes(): 
      raise ValueError('Nodes need to be in the graph') 
     self.get_edges()[origin].append(destination) 
     self.get_edges()[destination].append(origin) 
    def get_children(self, node): 
     """ 
     Returns the list of nodes node node is connected to 
     """ 
     return self.get_edges()[node] 

class GraphGeneration(object): 
    @classmethod 
    def gen_graph_from_text(cls, file): 
     ''' 
     Generate a graph from a txt. Each line of the txt begins with the source node and then the destination nodes follow 
     ''' 
     cls.__init__() 
     file = open(file, 'r') 
     for line in file: 
      origin = line[0] 
      destinations = line[1:-1] 
      cls.add_node(origin) 
      for destination in destinations: 
       cls.add_node(destination) 
       edge = Edge(origin, destination) 
       cls.add_connection(edge) 



graph = Graph.gen_graph_from_text(file) 

voglio che per restituire un grafico in cui i nodi ed i bordi sono generati dal file. Il metodo che ho scritto non funziona, non so se ha senso. Quello che voglio fare è all'interno di quel metodo per usare il metodo __init__ di Graph, ma poi aggiungere bordi e nodi dal file. Potrei semplicemente scrivere un metodo a livello di istanza per farlo, ma ho in mente altri inizializzatori alternativi.

Grazie!

+1

tua classe 'GraphGeneration' eredita solo da Object, per cui i suoi' cls .__ init __() 'non avrà nessuna delle cose grafico che si sta definendo. Qualche ragione per cui non è possibile renderlo una funzione? –

+0

Ho anche altri costruttori che voglio creare come creare un grafo di m nodi e quindi collegarli in base alle probabilità. Come dici tu, potrei implementare tutti questi metodi in istanza, ho pensato che sarebbe stato interessante averlo nei costruttori e avrei potuto imparare allo stesso tempo come fare i costruttori alternativi in ​​Python. – FranGoitia

risposta

5

All'interno dei costruttori alternativi, utilizzare cls per creare la nuova istanza della classe. Quindi, usa semplicemente self come faresti normalmente e restituiscilo alla fine.

NOTA: cls è un riferimento alla classe stessa, non all'istanza come ci si aspetta. La sostituzione di tutte le occorrenze di cls con self, ad eccezione della creazione di un'istanza, dovrebbe fornire il risultato desiderato. Per esempio,

@classmethod 
def gen_graph_from_text(cls, file): 
    self = cls() 
    file = open(file, 'r') 
    for line in file: 
     origin = line[0] 
     destinations = line[1:-1] 
     self.add_node(origin) 
     for destination in destinations: 
      self.add_node(destination) 
      edge = Edge(origin, destination) 
      self.add_connection(edge) 
    return self 
Problemi correlati