Python打印变量的值显示< __ main __。元素对象位于0x10071d5d0>

时间:2017-08-03 21:34:00

标签: python

您好我正在尝试打印" temp"变量所以我使用print(temp)

def delete_first(self):
    if self.head:
        deleted_element = self.head
        temp = deleted_element.next
        print(temp)
        self.head = temp
        return deleted_element
    else:
        return None

为什么我会得到这样的输出?这是内存中的对象地址吗?我修复它,以便打印出更有意义/可读的对象名称?

  <__main__.Element object at 0x10071d5d0>

完整代码:

class Element(object):
    def __init__(self, value):
        self.value = value
        self.next = None


class LinkedList(object):
    def __init__(self, head=None):
        self.head = head

    def append(self, new_element):
        current = self.head
        if self.head:
            while current.next:
                current = current.next
            current.next = new_element
        else:
            self.head = new_element

    def insert_first(self, new_element):
        new_element.next = self.head
        self.head = new_element

    def delete_first(self):
        if self.head:
            deleted_element = self.head
            temp = deleted_element.next
            print(temp)
            self.head = temp
            return deleted_element
        else:
            return None


class Stack(object):
    def __init__(self, top=None):
        self.ll = LinkedList(top)

    def push(self, new_element):
        self.ll.insert_first(new_element)

    def pop(self):
        return self.ll.delete_first()


# Test cases
# Set up some Elements
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)

# Start setting up a Stack
stack = Stack(e1)

# Test stack functionality
stack.push(e2)
stack.push(e3)
print stack.pop().value
print stack.pop().value
print stack.pop().value
print stack.pop()
stack.push(e4)
print stack.pop().value

完整输出:

&lt; main .Element对象位于0x10071d5d0&gt; 3 &lt; main .Element对象位于0x10071d590&gt; 2 没有 1 没有 没有 4

1 个答案:

答案 0 :(得分:-1)

您需要为此类定义__str__方法(当然,如果您拥有它),例如Java中的toString()

例如:

class Element():
  attr_1 = 0
  attr_2 = 0
  def __str__(self):
    return '%s, %s' % (self.attr_1, self.attr_2)