-1

as I am trying to do my python programming, I didn't know how to solve the situation in this case

class Node:
    def __init__(self, name):
        self.name = name
        self.neighbours = []

a = Node('a')
b = Node('b')
c = Node('c')
d = Node('d')
e = Node('e')

a.neighbours = [d]
b.neighbours = [d, e]
c.neighbours = [e]
d.neighbours = [e]
e.neighbours = [a]

node_rela = {}
node_rela[a.name] = a.neighbours

print(node_rela)

The a.name is successfully shown as 'a', but I don't know why it can't apply to a.neighbours

{'a': [<__main__.Node object at 0x000002424BF53CD0>]}

How to solve the problem in this situation

Thanks a lot

EmptyMind
  • 1
  • 3
  • "I didn't know how to solve the situation in this case" What "situation"? What happens when you run the code? What do you want to happen instead? Why? Why do you think the actual behaviour is a problem? Please read [ask] and *ask a question*. – Karl Knechtel Nov 26 '21 at 16:36

1 Answers1

2

With

print(node_rela)

you're printing a dictionary.

With

print(a.name)

you're printing a string ("a").

With

print(a)

you're printing an object.

With

print(a.neighbours)

you're printing a list.

If you want the Node objects to print differently than their default, learn about __str__ and __repr__.

It could look like this, for example:

def __repr__(self):
    neighbours = ", ".join(f"'{n.name}'" for n in self.neighbours)
    return f"Node('{self.name}' with neighbours {neighbours})"
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • what should I return in __repr__? when i do return self.neighbour it appears TypeError: __repr__ returned non-string (type list) – EmptyMind Nov 26 '21 at 16:51
  • @EmptyMind: the error message says all: you returned a list but you're supposed to return a string. – Thomas Weller Nov 27 '21 at 08:24