Python中棘手的继承问题

2024-09-30 16:29:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python创建两种类型的堆栈(后进先出技术)。其中一个(Stack master类)是样板堆栈类,另一个(CountingStack类)继承自master类,但也有一个计算pop()调用的方法

但是,当实例化CountingStack类的对象时,它似乎不会继承master类中的“\uu stk”属性。此列表是充当堆栈的实际容器本身

我得到的错误是:

Traceback (most recent call last):
  File "main.py", line 31, in <module>
    stk.pop()
  File "main.py", line 24, in pop
    self.__stk.pop()
AttributeError: 'CountingStack' object has no attribute '_CountingStack__stk'

我的剧本如下:

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

    def push(self, val):
        self.__stk.append(val)

    def pop(self):
        val = self.__stk[-1]
        del self.__stk[-1]
        return val


class CountingStack(Stack):
    def __init__(self):
        Stack.__init__(self)
        self.__pop_counter__ = 0
        self.__push_counter__ = 0

    def get_counter(self):
        return self.__pop_counter__

    def pop(self):
        self.__stk.pop()
        self.__pop_counter__ += 1
    

stk = CountingStack()
for i in range(100):
    stk.push(i)
    stk.pop()
print(stk.get_counter())

老实说,我不知道脚本为什么要寻找一个名为“_CountingStack_ustk”的属性,除了它是作为继承结果生成的子类属性之外

提前谢谢


Tags: inselfmaster属性initstack堆栈def
1条回答
网友
1楼 · 发布于 2024-09-30 16:29:30

前缀为__的名称会精确地进行名称更改,以便它们对子类中的属性不可见或不受其影响。除非您有充分的理由使用它们,否则只需使用带有_前缀的名称来表示私有属性

此外,不要发明你自己的dunder(__name__)名字;它们是为Python实现保留的

最后,CountingStack.pop必须显式返回由self._stk.pop返回的值

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

    def push(self, val):
        self._stk.append(val)

    def pop(self):
        val = self._stk[-1]
        del self._stk[-1]
        return val


class CountingStack(Stack):
    def __init__(self):
        Stack.__init__(self)
        self._pop_counter = 0
        self._push_counter = 0

    def get_counter(self):
        return self._pop_counter

    def pop(self):
        self._pop_counter += 1
        return self._stk.pop()

然而,更好的是,CountingStack.pop应该按照Stack.pop来实现,它应该使用list.pop而不是使用del。同样地,对于CountingStack.push(我假设您希望给出_push_counter的定义)

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

    def push(self, val):
        self._stk.append(val)

    def pop(self):
        return self._stk.pop()


class CountingStack(Stack):
    def __init__(self):
        super().__init__()
        self._pop_counter = 0
        self._push_counter = 0

    def get_counter(self):
        return self._pop_counter

    def pop(self):
        self._pop_counter += 1
        return super().pop()

    def push(self, val):
        self._push_counter += 1
        super().push(val)

相关问题 更多 >