Adil.R Adil.R - 1 year ago 93
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 "", line 108, in <module>
File "", line 29, in add_vertex
if isinstance(vertex,Vertex) and 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): = 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:

class Graph:

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

def add_vertex(self,vertex):
if isinstance(vertex,Vertex) and not in self.vertices:
self.vertices[] = vertex
return True
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:
if key == v:
return True
return False

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

Answer Source

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       # <---

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download