使用内置的Stask类The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index
如果必须为在堆栈中添加元素提供自定义接口,则可以添加以下单个方法:class Stack(list):
def push(self, *args, **kwargs):
self.append(*args, **kwargs)
打印对象
函数如何工作?All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.
函数真正的作用是什么?If neither encoding nor errors is given, str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object).
这意味着您Stack必须支持__str__()方法,如果它没有这样的__repr__()将被使用。A class can control what this function returns for its instances by defining a repr() method.
也请阅读以下答案,它们以不同的方式描述了我的想法:
摘要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)