【发布时间】:2019-03-12 07:04:03
【问题描述】:
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 中的类实例化如何在同一个类中完成?
【问题讨论】:
-
为什么不能从类的方法内部创建类的实例?这不像类和方法是需要相互配合的物理对象。
-
我想这是不允许的,因为从同一个类中创建一个类的实例可能有一个无限循环?这样的事情也可以吗?类图:def __init__(self):g = Graph()
-
整个“内部”的概念很奇怪。你明白代码和对象是两个完全不同的东西,对吧?一个对象不能真正在一个函数的“内部”。而且该函数也不完全在类“内部”。
标签: python python-3.x oop