Python中的替代构造函数
我正在玩图形,并编写了一个用于创建图形的mixin模块。我想在其中有一些替代构造函数。 这就是我所拥有的:Python中的替代构造函数,python,oop,object,constructor,Python,Oop,Object,Constructor,我正在玩图形,并编写了一个用于创建图形的mixin模块。我想在其中有一些替代构造函数。 这就是我所拥有的: class Graph(GraphDegree, GraphDegreePlot, GraphGeneration, object): def __init__(self): self.nodes = set([]) self.edges = {} def get_nodes(self): """ get no
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的\uuuu init\uuuu
方法,然后从文件中添加边和节点。我可以编写一个实例级方法来实现这一点,但我还考虑了其他可选的初始值设定项
谢谢 在备用构造函数中,使用
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
您的
GraphGeneration
类仅从对象继承,因此它的cls.\uuu init\uuu()
将不包含您定义的任何图形内容。有什么原因不能让它成为一个函数吗?我还有其他的构造函数,比如创建一个m个节点的图,然后根据概率将它们连接起来。正如您所说,我可以在实例中实现所有这些方法,我只是认为在构造函数中使用它会很酷,同时我可以学习如何在Python中使用其他构造函数。