Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

Creating a class with push and pop methods in Python

I am trying to create a Python object from the class below, but when I call the method popit(), I am getting a None. Any help as to what I miss or do wrong is appreciated.

class Stack:

def __init__(self, *item):
    self.stack = []
def pushit(self, item):
    if len(self.stack) == 9:
        print("Stack is full: " + self.stack)
    else:
        print(self.stack.append(self.item))
        
def popit(self):
    if self.stack == []:
        print("Stack underflow: " + self.stack)
    else:
        print(self.stack.pop())
question from:https://stackoverflow.com/questions/65838120/creating-a-class-with-push-and-pop-methods-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your methods -- both of them -- don't return anything. What I would do to sort this is:

class Stack:
    def __init__(self):
        self.stack = []

    def pushit(self, item):
        if len(self.stack) == 9:
            print("Stack is full: " + self.stack)
            return None
        else:
            print(self.stack.push(self.item))
            return self.item
        
    def popit(self):
        if self.stack == []:
            print("Stack underflow: " + self.stack)
            return None
        else:
            ret = self.stack.pop()
            print(ret)
            return ret

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...