在Python 3中打印地址而不是值

时间:2018-10-24 05:03:01

标签: python python-3.x

class ListNode:
    def __init__(self,x):
        self.val = x
        self.next = None


class Solution:
    def addTwoNumbers(self,l1, l2):
        cur = l1
        num1 = ""
        num2 = ""
        finalNum = 0
        while cur != None:
            num1 = num1 + str(cur.val)
            cur = cur.next

        cur = l2
        while cur != None:
            num2 = num2 + str(cur.val)
            cur = cur.next

        num1 = num1[::-1]
        num2 = num2[::-1]

        finalNum = int(num1) + int(num2)
        finalNum = str(finalNum)[::-1]

        l3 = ListNode(int(finalNum[0]))
        cur = l3

        for i in finalNum[1:]:
            node = ListNode(int(i))
            cur.next = node
            cur = cur.next
        return l3


def main():
    numbers=Solution()
    l1=ListNode(234)
    l2=ListNode(465)
    obj=numbers.addTwoNumbers(l1,l2)
    print(str(obj))

main()

打印内存地址,而不是python 3中的值

我正在尝试在我的Pycharm中运行以上代码,并打印出内存地址而不是值。有人可以指导我做错了什么地方吗?

2 个答案:

答案 0 :(得分:0)

您的函数addTwoNumbers()返回l3,它是一个对象ListNode

您对ListNode的定义:

class ListNode:
    def __init__(self,x):
        self.val = x
        self.next = None

您的值x保存在self.val中。因此,您需要添加.val来打印对象的值:

...

def main():
    numbers=Solution()
    l1=ListNode(234)
    l2=ListNode(465)
    obj=numbers.addTwoNumbers(l1,l2)
    print(str(obj.val))

...

答案 1 :(得分:0)

您需要为__str__()类定义ListNode方法,以便Python知道如何打印此特定对象。如果不知道,它只会打印一个通用的对象描述:

class ListNode:
    def __init__(self,x):
        self.val = x
        self.next = None
    def __str__(self):
        return str(self.val)