如何使用Python封装实现Stack?

我已经在python中实现了堆栈数据结构,其中maxsize,top和arr这些是Stack类中的实例变量。 通过setter方法更改maxsize和top变量。与在C ++或Java中一样,当我们定义堆栈或队列时,我们有一些私有变量,我们不想在类外部直接访问它们,并且值不应更改。通过在类中编写getter和setter,我设法使变量top和maxsize表现得像private。

我如何在Python中实现相同的事情,即使用对象无法在类外更改包含堆栈元素的实例变量arr。

有什么办法可以将arr变量设为私有?还是需要其他一些本机数据类型用于Python中的Stack实现?

堆栈实现:

class Stack:
    def __init__(self, maxsize):
        self.maxsize = maxsize
        self.top = -1
        self.arr = []

    @property
    def maxsize(self):
        return self.__maxsize

    @maxsize.setter
    def maxsize(self, maxsize):
        if maxsize < 1:
            maxsize = 1
        if not getattr(self, 'maxsize', None):
            self.__maxsize = maxsize

    @property
    def top(self):
        return self.__top

    @top.setter
    def top(self, top):
        if getattr(self, 'top', -1) < self.maxsize and top < self.maxsize and top >= -1:
            if abs(getattr(self, 'top', -1) - top) in (0, 1):
                self.__top = top

    def is_empty(self):
        return self.top == -1

    def is_full(self):
        return self.top == self.maxsize - 1

    def push(self, ele):
        if self.is_full():
            return
        self.top += 1
        self.arr.append(ele)
        return ele

    def pop(self):
        if self.is_empty():
            return
        ele = self.arr[self.top]
        del self.arr[self.top]
        self.top -= 1
        return ele

    def display(self):
        print(*self.arr, sep=', ')


s = Stack(10)

s.push(23)
s.push(45)
s.push(34)

print("before changing arr >>>>> ")
s.display()
s.arr = [3,3,3,3,3,3,3,3] # this line breaking the stack implementation
                          # either it should raise error or should not change the
                          # value of variable which holding stack elements
print("after changing arr >>>>> ")
s.display()

输出:

before changing arr >>>>> 
23, 45, 34
after changing arr >>>>> 
3, 3, 3, 3, 3, 3, 3, 3
评论