1

I'm new in Python, and didn't find a similar previous question here. My question is how can I see the real contents of the list node_list here, instead the memory address?? (which actually includes node1, node2 names and its neighbors)

class node:
  def __init__(self, name):
    self.name=name
    self.neighbors={}

  def update(self, name, weight):
    if name in self.neighbors:
      self.neighbors[name]=max(int(weight),int(self.neighbors[name]))
    elif self.name==str(name):
      print ("this is prohibited to add a key name as an existed name")
    else:
      self.neighbors[name] = str(weight)

node_list = []

node1 = node('1')
node_list.append(node1)
node1.update('2',10)
node1.update('4',20)
node1.update('5',20)

node2 = node('2')
node_list.append(node2)
node2.update('3',5)
node2.update('4',10)

print(node1.name)        #  That's OK - prints:  1
print(node1.neighbors)   #  That's OK - prints:  {'2': '10', '4': '20', '5': '20'}
print(node_list)         #  Not OK: prints:[<__main__.node object at 0x7f572f860860>, <__main__.node object at 0x7f572f860dd8>]  
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Eli
  • 31
  • 1
  • 2

1 Answers1

1

I think you would have to create a __str__ method for nodes inside their class definition. Otherwise, Python automatically prints the memory address.

Here is a similar question.

How to print a class or objects of class using print()?

Pranav E
  • 93
  • 3
  • 11
  • Thanks, but I already have seen this answer, but it's not related to a list contents. Is the implementation should be different ? what should I write in __str__ method that makes it work (print(node_list)) ? – Eli Jul 27 '18 at 19:17
  • You need to define the __repr__() command. Calling the str command on a list returns a string composed of calling the repr command on all the objects that the list contains, so you would need to make the __repr__() command the same as your string command. Hopefully, this works. Sorry for the initial misleading comment. @Eli – Pranav E Jul 27 '18 at 22:36