简体   繁体   English

如何重载 __repr__ 方法以显示链表堆栈中的所有项目?

[英]How can I overload the __repr__ method to display all items in a linked list Stack?

I've created my Node and Stack classes, but I can't figure out how I can display the repr in the Stack class in order to be able to print all items currently in the stack?我已经创建了我的 Node 和 Stack 类,但我无法弄清楚如何在 Stack class 中显示repr以便能够打印堆栈中当前的所有项目? I've been trying to concatenate the nodes but I'm not sure how since the Stack() doesn't allow iterating through the way a list does?我一直在尝试连接节点,但我不确定如何连接,因为 Stack() 不允许通过列表的方式进行迭代?

The stack works as it should, I just don't know how to display it's contents?堆栈正常工作,我只是不知道如何显示它的内容?

Here is my code:这是我的代码:

class Stack:
    class Node:
        def __init__(self, elem, next):
            self.elem = elem
            self.next = next
        
        def __repr__(self):
            return str(self.elem)
    
    def __init__(self):
        self._stack = None
        self._size  = 0
        
    
    def __repr__(self):
        # *Not sure how to implement this properly*
        s = ''
        for i in range(self._size):
            last = self._stack.elem
            s += (str(last))+ ', '
            self._stack.elem = self._stack.next
        return 
    
    def push(self, elem):
        if self._stack == None:
            self._stack = self.Node(elem, None)
            self._size += 1 
        else: 
            self._stack = self.Node(elem, self._stack)
            self._size += 1 
    
    def pop(self):
        if self._stack == None:
            raise Exception ('This Stack is empty!')
        else: 
            last = self._stack.elem
            self._stack = self._stack.next
            self._size -= 1
        return last
    
    def top(self):
        return  self._stack.elem
    
    def isEmpty(self):
        return self._size == 0

Example:例子:

s= Stack()
s.push(4)
s.push(9)
s.push("joe")
s
joe, 9, 9, 

Thank you in advance.先感谢您。

A way simpler implementation that avoids all the problems and pitfalls of your solution:一种更简单的实现方式,可以避免您的解决方案的所有问题和陷阱:

from typing import Iterable, Any


class Stack:
    def __init__(self, xs: Iterable = None):
        self._items = [] if xs is None else list(xs)

    def push(self, elem: Any):
        self._items.append(elem)

    def pop(self) -> Any:
        return self._items.pop()

    def top(self) -> Any:
        return self._items[-1]

    def isEmpty(self) -> bool:
        return not self._items

    def __repr__(self) -> str:
        typename = type(self).__name__
        return f'{typename}({self._items})'

    def __str__(self) -> str:
        return ', '.join(str(x) for x in self._items)


s = Stack()
s.push(4)
s.push(9)
s.push("joe")
print(s)
print(repr(s))

But note that there's little use to a class like this over just using a list like a stack to begin with.但是请注意,像这样的 class 比仅使用像堆栈这样的列表开始时几乎没有用处。

The output: output:

4, 9, joe
Stack([4, 9, 'joe'])

Note that this has the top element at the end, you could reverse it if you like of course.请注意,这在末尾有顶部元素,如果您愿意,当然可以将其反转。

If you insist on a working __repr__ for your specific implementation, using __repr__ as you intend in a non-standard way, something like this would work:如果你坚持为你的具体实现工作__repr__ ,按照你的意图以非标准方式使用__repr__ ,这样的事情会起作用:

    def __repr__(self):
        p = self._stack
        elems = []
        while p is not None:
            elems.append(p.elem)
            p = p.next
        return ', '.join(elems)

But note that there's several other issues with your implementation, other than this not being a correct __repr__ , as previously pointed out here and in the comments.但请注意,除了这不是正确的__repr__ ,您的实施还有其他几个问题,正如之前在此处和评论中指出的那样。 Your 'node' has a __repr__ which just returns its element value (which isn't a valid representation at all in most cases);您的“节点”有一个__repr__ ,它只返回其元素值(在大多数情况下根本不是有效表示); you seem to be using __repr__ where you're really after __str__ .你似乎在使用__repr__而你真正在使用__str__

If this were an assignment in programming class, I'm not sure I'd award a passing grade, depending on what the aim was.如果这是编程 class 中的作业,我不确定我是否会授予及格分数,具体取决于目标是什么。

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

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