Python中的替代构造函数 [英] Alternative Constructors in Python

查看:50
本文介绍了Python中的替代构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩图形,并编写了用于创建图形的mixin模块.我想在其中包含一些替代构造函数.这就是我所拥有的:

I'm playing with graphs and coded a mixin module for creating graphs. I want to have in it some alternative constructors. This is what I have:

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 __ 方法,然后从文件中添加边和节点.我可以编写一个实例级方法来做到这一点,但我还想着其他替代初始化器.

I want that to return a graph where nodes and edges are generated from the file. The method I wrote doesn't work, I don't know if it even makes sense. What I want to do is inside that method to use the __init__ method of Graph, but then add edges and nodes from the file. I could just write an instance level method to do this, but I have other altertive initializers in mind.

谢谢!

推荐答案

在替代构造函数中,使用 cls 创建该类的新实例.然后,只需像平常一样使用 self 并将其返回末尾即可.

Inside of your alternate constructors, use cls to create the new instance of the class. Then, just use self like you normally would and return it at the end.

注意: cls 是对类本身的引用,而不是您期望的实例.除了实例化以外,用 self 代替所有 cls 出现,应该会为您提供所需的结果.例如,

NOTE: cls is a reference to the class itself, not the instance like you're expecting. Replacing all occurrences of cls with self except for the instantiation should give you the result you want. E.g.,

@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中的替代构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆