Reputation: 408
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)
The above code seems to work fine, but I am confused how can the class instantiation in getTranspose be done from within the same class?
Upvotes: 5
Views: 7183
Reputation: 10219
It is because all the information to create an object of a class (i.e., its members and the amount of memory the require) is already known at the point when you call one of its methods (in this case getTranspose
).
If, however, you try to create an instance of the class in its own constructor, it will result in infinite recursion.
class A:
def __init__(self):
self.a = A() # This will lead to RecursionError being thrown
Upvotes: 4
Reputation: 37
That's because when you call the class Graph in your method, it's like calling the Graph constructor (the init method) with all its attributes, and since they all already declared, there's no reason why it shouldn't work I had the same issue once, but my programming teacher told me this and it makes sense
Upvotes: 0