簡體   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