Stack data structure in python

前端 未结 7 1472
轮回少年
轮回少年 2021-02-02 09:24

I have 2 issues with the code below:

  1. push(o) throws an exception TypeError: can only assign an iterable.
  2. Should I throw an exception if pop()

7条回答
  •  佛祖请我去吃肉
    2021-02-02 09:44

    You are right to use composition instead of inheritance, because inheritance brings methods in that you don't want to expose.

    class Stack:
      def __init__(self):
        self.__storage = []
    
      def isEmpty(self):
        return len(self.__storage) == 0
    
      def push(self,p):
        self.__storage.append(p)
    
      def pop(self):
        return self.__storage.pop()
    

    This way your interface works pretty much like list (same behavior on pop for example), except that you've locked it to ensure nobody messes with the internals.

提交回复
热议问题