python class method prints address of variable instead of its value

  linked-list, python

I’m trying to write a circular linked list with only 2 methods, push() and show(). but the show() method prints addresses instead of data

class Node:
    def __init__(self, data):
        self.data = data 
        self.next = None
        self.prev = None

class Circular_list:
    def __init__(self):
        self.head = Node(None)
        self.tail = Node(None)
        self.head.next = self.tail
        self.head.prev = self.tail
        self.tail.next = self.head
        self.tail.prev = self.head

    def push(self, data):
        node = Node(data)

        if self.head.data is None:
            self.head = node
            self.tail = node
        else:
            self.tail.next = node
            node.next = self.head
            node.prev = self.tail
            self.tail = node
            self.head.prev = self.tail
            
    def show(self):
        i = self.head
        for temp in range(4):
            print(i.data, end=' ')
            i = i.next
            temp += 1
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
list = Circular_list()
list.push(n1)
list.push(n2)
list.push(n3)
list.show() 

the output is <__main__.Node object at 0x000002A78EDD3FD0> <__main__.Node object at 0x000002A78EDD3F70> <__main__.Node object at 0x000002A78EDD3E80>
but it’s supposed to print 1 2 3

p.s: note that I originally wrote show() method with infinite while loop and it works just fine in terms of getting from tail to head. so i suppose it’s an OK circular linked-list. but unfortunately i can’t get the node’s data

Source: Python Questions

LEAVE A COMMENT