Fra*_*tia 5 python oop constructor object
我正在玩图形并编写一个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)
Run Code Online (Sandbox Code Playgroud)
我希望它返回一个图形,其中从文件生成节点和边.我写的方法不起作用,我不知道它是否有意义.我想要做的是在该方法中使用__init__Graph 的方法,然后从文件中添加边和节点.我可以写一个实例级方法来做到这一点,但我还有其他的替代初始化器.
谢谢 !
在备用构造函数内部,用于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
Run Code Online (Sandbox Code Playgroud)