简体   繁体   中英

how to instantiate a class and print the value

hope somebody can give me a hint here - so i have a Node class that should receive 1 mandatory value and one optional one. The idea is to return a linked list

class Node(object):
    def __init__(self, value, next_node = None):
        self.value = value
        self.next_node = next_node

    def get_next(self):
        return self.next_node

Now i'm using this class to create a linked list like:

Z = Node('Z')
Y = Node('Y', Z)
X = Node('X', Y)
W = Node('W', X)

Now I want to write a function that receives the head of the list and prints it:

def print_reverse(head):
    current = head
    my_list = []
    while current:
        current = current.next_node
        u = Node(current)
        my_list.append(u.value)
    print my_list

print_reverse(W)

The problem I'm facing is that i get back the memory address instead of the actual value.

[<__main__.Node object at 0x1033eb390>, <__main__.Node object at 0x1033eb350>, <__main__.Node object at 0x1033eb310>, None]

Basically I don't know how to instantiate the value of the Node. I would want to get back this

[ W, X, Y , Z, None]
class Node(object):
    def __init__(self, value, next_node = None):
        self.value = value
        self.next_node = next_node

    def get_next(self):
        return self.next_node

def print_reverse(head):
    current = head
    my_list = []
    my_list.append(current.value)
    while current.next_node != None:
        current = current.next_node
        my_list.append(current.value)
    print my_list

Z = Node('Z')
Y = Node('Y', Z)
X = Node('X', Y)
W = Node('W', X)
print_reverse(W)

This runs and prints ['W','X','Y','Z'] for me.

You need implement repr which should return a printable representation of the object. eg.

class Node(object):
    def __init__(self, value, next_node = None):
        self.value = value
        self.next_node = next_node

    def get_next(self):
        return self.next_node

    def __repr__(self):
        return self.value

https://docs.python.org/2/reference/datamodel.html#object. repr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM