繁体   English   中英

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

[英]how to instantiate a class and print the value

希望有人可以在这里给我一个提示-所以我有一个Node类,应该接收1个强制值和一个可选值。 这个想法是返回一个链表

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

现在,我正在使用此类创建链接列表,例如:

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

现在,我想编写一个接收列表头并打印的函数:

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)

我面临的问题是我找回了内存地址而不是实际值。

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

基本上我不知道如何实例化Node的值。 我想回去

[ 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)

这会为我运行并打印['W','X','Y','Z']。

您需要实现repr ,该实现应返回对象的可打印表示形式。 例如。

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。 再版

暂无
暂无

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

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