0

I'm trying to create several class instances of graphs and initialize each one with an empty set, so that I can add in-neighbors/out-neighbors to each instance:

class Graphs:
    
    def __init__(self, name, in_neighbors=None, out_neighbors=None):
        self.name = name
        
        if in_neighbors is None:
            self.in_neighbors = set()
        if out_neighbors is None:
            self.out_neighbors = set()
        
    def add_in_neighbors(self, neighbor):
        in_neighbors.add(neighbor)

    def add_out_neighbors(self, neighbor):
        out_neighbors.add(neighbor)
    
    def print_in_neighbors(self):
        print(list(in_neighbors))
            
graph_names = [1,2,3,33]

graph_instances = {}

for graph in graph_names:
    graph_instances[graph] = Graphs(graph)

However, when I try to add an in-neighbor:

graph_instances[1].add_in_neighbors('1')

I get the following error:

NameError: name 'in_neighbors' is not defined

I was following this SO question that has a class instance initialized with a list, but I couldn't figure out where I'm mistaken

Penguin
  • 1,923
  • 3
  • 21
  • 51

2 Answers2

0

Silly of me, but thanks to @Nick I solved it (was missing self.in_neighbors.add(neighbor)).

class Graphs:
    
    def __init__(self, name, in_neighbors=None, out_neighbors=None):
        self.name = name
        
        if in_neighbors is None:
            self.in_neighbors = set()
        if out_neighbors is None:
            self.out_neighbors = set()
        
    def add_in_neighbors(self, neighbor):
        self.in_neighbors.add(neighbor)

    def add_out_neighbors(self, neighbor):
        self.out_neighbors.add(neighbor)
    
    def print_in_neighbors(self):
        print(list(self.in_neighbors))
            
graph_names = [1,2,3,33]

graph_instances = {}

for graph in graph_names:
    graph_instances[graph] = Graphs(graph)

graph_instances[1].add_in_neighbors('1')
graph_instances[1].print_in_neighbors()
Penguin
  • 1,923
  • 3
  • 21
  • 51
  • 1
    You should also add an `else` clause for `if in_neighbors is None:` (and `out_`) so that a graph _can_ be initialised with neighbors. And you probably meant to add neighbors by their `name` and not `str(name)`: `1` vs the string `'1'`, since `1 != '1'` in Python. – aneroid Jan 02 '21 at 23:10
  • Ah yes, both really good points. For the first one I'll definitely add it- haven't even thought about that option. In regards to the second one, good point, I was actually just typing this one quickly to see if the initialization will work, but you're definitely right. – Penguin Jan 02 '21 at 23:18
0

Remember always type the "self." when you make a reference to a specific element of the class, in this cases you need to be very careful: in_neighbors out_neighbors

If you type this propierties of this way, this give an error. The correct way would be: self.in_neighbors self.out_neighbors

CesarCr300
  • 11
  • 1