【问题标题】:Alternative Constructors in PythonPython 中的替代构造函数
【发布时间】:2015-09-09 17:53:57
【问题描述】:

我正在玩图形并编写了一个用于创建图形的 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__ 方法,然后从文件中添加边和节点。我可以只编写一个实例级方法来执行此操作,但我想到了其他替代初始化器。

谢谢!

【问题讨论】:

  • 您的 GraphGeneration 类仅继承自 Object,因此其 cls.__init__() 不会包含您定义的任何图形内容。你有什么理由不能让它成为一个函数?
  • 我还想要创建其他构造函数,例如创建 m 个节点的图,然后根据概率连接它们。正如你所说,我可以在实例方法中实现所有这些,我只是认为在构造函数中使用它会很酷,同时我可以学习如何在 Python 中执行替代构造函数。

标签: python oop object constructor


【解决方案1】:

在您的备用构造函数中,使用cls 创建该类的新实例。然后,像往常一样使用self 并在最后返回它。

注意:cls 是对类本身的引用,而不是您期望的实例。用self 替换所有出现的cls,除了实例化应该会给你想要的结果。例如,

@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多