如何在python 3中打印堆栈元素



我必须使用类和all打印堆栈中的元素:

class Stack:
    def __init__(self):
        self.stack = []
    def push(self,element):
        self.stack.append(element)
    def pop(self):
        return self.stack.pop()
def st(n):
    s = Stack()
    for i in range(n,0,-1):
        s.push(i)
    #this is updated version now I want to print outside of the loop and 
    #it gives me this error : __main__.Stack instance at 0x7fe40d261710> 
    print s
if __name__ == '__main__':
   st(4)

出于某种原因而不是打印[4,3,2,1]它打印无

您的类没有定义__str____repr__方法,因此print使用默认表示。如果您希望Stack的实例打印为列表,请将以下定义添加到类中:

def __str__(self):
    return str(self.stack)

Stask类使用内置

使用列表作为堆栈https://docs.python.org/3/tutorial/datastructures.html#using-以堆栈形式列出

list方法可以很容易地将列表用作堆栈,其中添加的最后一个元素就是检索到的第一个元素("后进先出"(。要将一个项添加到堆栈顶部,请使用append((。要从堆栈顶部检索项目,请使用pop((而不使用显式索引

如果你必须为在堆栈中添加元素提供自定义接口,你可以添加这样的单一方法:

class Stack(list):
    def push(self, *args, **kwargs):
        self.append(*args, **kwargs)

打印对象

print函数的行为如何

让我们看看关于print函数的文档https://docs.python.org/3/library/functions.html#print

所有非关键字参数都会像str((那样转换为字符串,并写入流中,用sep分隔,后跟end。

str()的真正功能是什么

如果既没有给出编码也没有给出错误,str(object(将返回object.__str__(),这是对象的"非正式">或可良好打印的字符串表示。对于字符串对象,这是字符串本身。若对象并没有__str__()方法,则str((返回返回repr(object)

这意味着你的Stack必须支持__str__()方法,如果它没有这样的__repr__(),就会被使用。

如果你不相信我的话,看看repr(object)文档https://docs.python.org/3/library/functions.html#repr

类可以通过定义repr((方法来控制此函数为其实例返回的内容。

还请阅读这些答案,这些答案以不同的方式描述了我的想法:

  • Python中__str__和__repr_之间的差异将解释实际用例
  • Python中__str__和__repr_之间的差异将解释每个方法的含义

摘要

class Stack(list):
    """
    Implaments stack interface to access data by inheriting buil-in list
    object.
    Note: all parent methods will be accessable in stack instance.
    """
    def push(self, *args, **kwargs):
        """
        Delegate behaviour to parrent class.
        """
        self.append(*args, **kwargs)
    def __str__(self):
        """
        Because of using list as parent class for stack, our last element will
        be first for stack, according to FIFO principle. So, if we will use
        parent's implementation of str(), we will get reversed order of
        elements.
        """
        #: You can reverse elements and use supper `__str__` method, or 
        #: implement it's behavior by yourself.
        #: I choose to add 'stack' in the begging in order to differ list and
        #: stack instances.
        return 'stack [{}]'.format(', '.join(reversed(self)))

def example_of_usage():
    #: Here we just using parent's list initialization functionality to init
    #: stack from iterable (in our case - list).
    s = Stack(['last', 'first'])
    #: output> stack ['fist', 'last']
    print(s)
    s.push('very first')
    #: output> stack ['very first', 'fist', 'last']
    print(s)
print s.push(i)

参见行,s.push()附加值并返回None。所以你最终打印了None

pop()有效,因为与append()不同,它返回一个值。

因此,更改函数定义如下:

def push(self,element):
    self.stack.append(element)
    return self.stack 
return "".join(self.stack_objects)

最新更新