Eli
Eli

Reputation: 31

Python - How to print a list's contents that have class objects inside?

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

Upvotes: 1

Views: 136

Answers (1)

Pranav E
Pranav E

Reputation: 93

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()?

Upvotes: 1

Related Questions