我必须使用类和所有内容在堆栈中打印元素:
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] 它打印无
答案 0 :(得分:2)
您的课程未定义__str__
或__repr__
方法,因此print
使用默认表示。如果您希望将Stack
的实例打印为列表,请将以下定义添加到您的类中:
def __str__(self):
return str(self.stack)
答案 1 :(得分:1)
将列表用作堆栈https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks
list方法可以很容易地将列表用作堆栈,其中添加的最后一个元素是检索到的第一个元素(“last-in,first-out”)。要将项添加到堆栈顶部,请使用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__()
,这是“非正式”或对象的可打印字符串表示。对于字符串对象,这是字符串本身。如果object没有__str__()
方法,则str()会回退到返回repr(object)
。
这意味着您Stack
必须支持__str__()
方法,如果没有此类__repr__()
将被使用。
如果您不相信我的话https://docs.python.org/3/library/functions.html#repr
,请查看repr(object)
个文档
类可以通过定义 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)
答案 2 :(得分:0)
print s.push(i)
查看该行,s.push()
追加该值并返回None
。所以你最终打印None
您的pop()
有效,因为与append()
不同,它会返回一个值。
所以,改变那样的函数定义:
def push(self,element):
self.stack.append(element)
return self.stack
答案 3 :(得分:0)
return "".join(self.stack_objects)