python - 从同一类定义中实例化 python 类

标签 python python-3.x oop

from collections import defaultdict 

#This class represents a directed graph using adjacency list representation 
class Graph: 
    def __init__(self,vertices): 
        self.V= vertices #No. of vertices 
        self.graph = defaultdict(list) # default dictionary to store graph 

    # function to add an edge to graph 
    def addEdge(self,u,v): 
        self.graph[u].append(v) 

    # Function that returns reverse (or transpose) of this graph 
    def getTranspose(self): 
        g = Graph(self.V) 

        # Recur for all the vertices adjacent to this vertex 
        for i in self.graph: 
            for j in self.graph[i]: 
                g.addEdge(j,i) 
        return g 

g = Graph(5)
g.addEdge(1, 0)
g.addEdge(0, 2)
g.addEdge(2, 1) 
g.addEdge(0, 3) 
g.addEdge(3, 4) 

上面的代码似乎工作正常,但我很困惑如何在同一个类中完成 getTranspose 中的类实例化?

最佳答案

这是因为当您调用其方法之一时,创建类对象的所有信息(即其成员和所需的内存量)都已经知道(在本例中为 getTranspose ) .

但是,如果您尝试在类自己的构造函数中创建该类的实例,则会导致无限递归。

class A:
    def __init__(self):
        self.a = A()  # This will lead to RecursionError being thrown

关于python - 从同一类定义中实例化 python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52688203/

相关文章:

c# - 更好的重载构造函数设计?

java - java父类(super class)调用的效果

python - 根据 2(或更多列值)查找下一个相关行

python - 用 uuid 替换整数 id 字段

Python将对象属性写入文件

python - 如何从 Python 3.4.2 控制 ImageJ

python - 导入错误 : No module named xxx after setup.

python - Python 中基于时间的 for 循环

python - 导入错误 : cannot import name 'QStringList' in PyQt5

python - Python-如何在两个方向上对自己的类执行操作?