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

Roh*_*gam 5 python oop python-3.x

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) 
Run Code Online (Sandbox Code Playgroud)

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

lig*_*ist 4

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

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

class A:
    def __init__(self):
        self.a = A()  # This will lead to RecursionError being thrown
Run Code Online (Sandbox Code Playgroud)