Python。它不是打印 Stack 对象的实际值,而是 returns 该对象的地址
Python. Instead of printing actual values from the Stack object it returns an address of that object
不是打印 Stack 对象的实际值,而是 returns 该对象的地址。
class 堆栈:
def init(self):
self._theItems = 列表()
def push(self, item):
self._theItems.append(item)
def pop(self):
assert not self.is_empty(), "Cannot pop from an empty stack"
return self._theItems.pop()
def get_top(self):
assert not self.is_empty(), "Cannot peek at an empty stack"
return self._theItems[-1]
def is_empty(self):
return len(self._theItems) == 0
def display(self):
return self
那是因为您还没有定义任何repr 或str 方法。请按如下所示修改程序:
def __str__(self):
return f'The customized stack has values: {self._theItems}'
def __repr__(self):
return self.__str__()
def display(self):
return self.__repr__()
if __name__ == "__main__":
customized_stack = Stack()
customized_stack.init()
customized_stack.push(10)
customized_stack.push(20)
customized_stack.push(30)
customized_stack.push(40)
print(customized_stack)
当你 运行 它时,你会得到:
The customized stack has values: [10, 20, 30, 40]
不是打印 Stack 对象的实际值,而是 returns 该对象的地址。
class 堆栈: def init(self): self._theItems = 列表()
def push(self, item):
self._theItems.append(item)
def pop(self):
assert not self.is_empty(), "Cannot pop from an empty stack"
return self._theItems.pop()
def get_top(self):
assert not self.is_empty(), "Cannot peek at an empty stack"
return self._theItems[-1]
def is_empty(self):
return len(self._theItems) == 0
def display(self):
return self
那是因为您还没有定义任何repr 或str 方法。请按如下所示修改程序:
def __str__(self):
return f'The customized stack has values: {self._theItems}'
def __repr__(self):
return self.__str__()
def display(self):
return self.__repr__()
if __name__ == "__main__":
customized_stack = Stack()
customized_stack.init()
customized_stack.push(10)
customized_stack.push(20)
customized_stack.push(30)
customized_stack.push(40)
print(customized_stack)
当你 运行 它时,你会得到:
The customized stack has values: [10, 20, 30, 40]