python - Python 中的替代构造函数

标签 python oop object constructor

我正在研究图表并编写了一个用于创建图表的混合模块。我想在其中包含一些替代构造函数。 这是我的:

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__ 方法,然后从文件中添加边和节点。我可以只编写一个实例级方法来执行此操作,但我想到了其他替代初始化程序。

谢谢!

最佳答案

在您的替代构造函数中,使用 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

关于python - Python 中的替代构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31011143/

相关文章:

不使用 db.eval() 的 django 中用于 mongodb 的 Python ORM

python - Pandas 中 "in"关键字或子查询的等价物

perl - 现代 Perl : how to implement Redispatching Methods in AUTOLOAD()?

javascript - 在 Node.js 中创建模块的副本而不是实例

mysql - mysql 中的组列

python - 在没有 json 库的情况下在 python 中解析 JSON 对象(仅使用正则表达式)

python导入模块依赖错误

c++ - 创建类成员函数

javascript - Js面向对象: private variable from a class

javascript - Javascript中如何将字符串转换为对象?