我试图用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”的属性,除了它是作为继承结果生成的子类属性之外
提前谢谢
前缀为
__
的名称会精确地进行名称更改,以便它们对子类中的属性不可见或不受其影响。除非您有充分的理由使用它们,否则只需使用带有_
前缀的名称来表示私有属性此外,不要发明你自己的dunder(
__name__
)名字;它们是为Python实现保留的最后,
CountingStack.pop
必须显式返回由self._stk.pop
返回的值然而,更好的是,
CountingStack.pop
应该按照Stack.pop
来实现,它应该使用list.pop
而不是使用del
。同样地,对于CountingStack.push
(我假设您希望给出_push_counter
的定义)相关问题 更多 >
编程相关推荐