Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...