我正在玩图形并编写一个mixin模块来创建图形。我想在其中有一些替代构造函数。 这就是我所拥有的:
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)
我想要返回一个图表,其中从文件生成节点和边。我写的方法不起作用,我不知道它是否有意义。我想要做的是在该方法中使用Graph的__init__
方法,然后从文件中添加边和节点。我可以编写一个实例级方法来实现这一点,但我还有其他的初始化方法。
谢谢!
答案 0 :(得分:5)
在备用构造函数内部,使用cls
创建类的新实例。然后,像往常一样使用self
,最后返回。
注意:cls
是对类本身的引用,而不是您期望的实例。除了实例化之外,用cls
替换所有出现的self
应该可以得到您想要的结果。如,
@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