简体   繁体   English

如何实例化一个类并打印值

[英]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. 希望有人可以在这里给我一个提示-所以我有一个Node类,应该接收1个强制值和一个可选值。 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. 基本上我不知道如何实例化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. 这会为我运行并打印['W','X','Y','Z']。

You need implement repr which should return a printable representation of the object. 您需要实现repr ,该实现应返回对象的可打印表示形式。 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. https://docs.python.org/2/reference/datamodel.html#object。 repr 再版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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