python - 用户调用的“Create_stack”函数
问题描述
我需要为 Stack 类创建一个函数,用户需要在使用它之前创建一个堆栈。这是我第二次使用类,所以错误可能很简单。create 函数应该能够创建一个空列表以供以后使用。
class Stack:
def __init__(self):
self.stack = None
#-----------------------------------------------------------------------------
#The problem is right here (I think)
def create_stack(self):
self.stack = list()
return self.stack
#-----------------------------------------------------------------------------
def add_data(self):
if self.stack is not None:
print('Insert the following requirements.')
requires = ['Name', 'Last Name', 'Enrollment']
temp = list()
for i in requires:
element = str(input('{}: '.format(i)))
temp.append(element)
final = Node(temp[0], temp[1], temp[2])
print(final.data())
else:
print('To add data you need to create a stack.')
我的代码是
class Node:
def __init__(self, first, last, number):
self.first = first
self.last = last
self.number = number
self.mail = 'a' + number + '@company.com'
def data(self):
return '{} {} {}'.format(self.first, self.last, self.mail)
class Stack:
def __init__(self):
self.stack = None
#-----------------------------------------------------------------------------
#The problem is right here (I think)
def create_stack(self):
self.stack = list()
return self.stack
#-----------------------------------------------------------------------------
def add_data(self):
if self.stack is not None:
print('Insert the following requirements.')
requires = ['Name', 'Last Name', 'Enrollment']
temp = list()
for i in requires:
element = str(input('{}: '.format(i)))
temp.append(element)
final = Node(temp[0], temp[1], temp[2])
print(final.data())
#self.push(final.data())
else:
print('To add data you need to create a stack.')
#def push(self, info):
""" stud_1 = Stack('Someone', 'Here', '123456')
print(stud_1.data()) """
Stack().create_stack() #this is a list but the class does not recognize it
Stack().add_data()
第一个实例是将信息分配给单个节点,然后该节点将成为堆栈上的第一项。当我使用 Stack 类时,首先没有堆栈,这很好,因为用户必须创建它。这就是为什么堆栈最初是 None 的原因,然后我创建了一个方法来将其从“None”更改为空列表,但程序无法识别该更改,因此,列表在创建之前仍然是空的。
对于一个简单的堆栈就像
class Stack:
def __init__(self):
self.stack = list() #change these lines throughout the last code to test it
解决方案
推荐阅读
- php - 如何在没有身份验证的情况下创建 JWT 令牌
- mysql - Google Sheets JDBC 脚本中的西里尔文数据库内容
- sql - 如何根据在 oracle 中具有空值的列从两个不同的列中进行选择
- python - Pygame 表面位置似乎与屏幕上的位置不同?
- python - Cython - 动态 2D C++Array 的 Memoryview
- mongodb - MongoDB按偶数元素将数组拆分为N元素数组
- c# - 寻找着陆点
- json - Nil 与预期的参数类型“JSON”不兼容
- c# - 用于 IList 的 WPF 数据网格
- 无法添加新值 - authentication - 我重新启动节点红色,但用户仍然登录