Adil.R Adil.R - 1 month ago 11
Python Question

Python object has no attribute 'variable name'

I have created a graph class in python.The problem I'm having is that when I try to use my graph class i get this error :

Traceback (most recent call last):
File "code.py", line 108, in <module>
g.add_vertex(Vertex(word1))
File "code.py", line 29, in add_vertex
if isinstance(vertex,Vertex) and vertex.name not in self.vertices:
AttributeError: 'Graph' object has no attribute 'vertices'


I don't know why am i getting this error, although i have made vertices dictionary in my graph. Any help guys?

Graph :

class Vertex:
def __init__(self,n):
self.name = n
self.neighbors = list()
self.discovery = 0
self.finish = 0
self.color = 'black'

def add_neighbor(self,v):
nset = set(self.neighbors)
if v not in nset:
self.neighbors.append(v)
self.neighbors.sort()


class Graph:

def __init__(self):
vertices = {}
time = 0

def add_vertex(self,vertex):
if isinstance(vertex,Vertex) and vertex.name not in self.vertices:
self.vertices[vertex.name] = vertex
return True
else:
return False

def add_edge(self,u,v):
if u in self.vertices and v in self.vertices:
for key, value in self.vertices.items():
if key == u:
value.add_neighbor(v)
if key == v:
value.add_neighbor(u)
return True
else:
return False

def print_graph(self):
for key in sorted(list(self.vertices.keys())):
print(key + str(self.vertices[key].neighbors))

Answer

You should qualify attributes names with self. when creating the attributes. Otherwise, they become local variables.

class Graph:

    def __init__(self):
        self.vertices = {}  # <---
        self.time = 0       # <---

    ...