首页 > 解决方案 > 用户调用的“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

标签: pythonfunctionclassstacknodes

解决方案


推荐阅读