Python OOB:不理解子类

Python OOB: Not understanding subclasses

我目前正在研究 edube.org 课程(Python Essentials 2(中级,v.2.0)。

该任务是关于以面向对象的方式对堆栈进行编程。到目前为止,我们有一个 push 和一个 pop 方法,还有一个简单的堆栈,我们可以填充和取出最后一项。现在应该扩展它以能够显示堆栈中值的总和。实验室给出的完整代码如下:

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

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

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


class AddingStack(Stack):
    def __init__(self):
        Stack.__init__(self)
        self.__sum = 0

    def get_sum(self):
        return self.__sum

    def push(self, val):
        self.__sum += val
        Stack.push(self, val)

    def pop(self):
        val = Stack.pop(self)
        self.__sum -= val
        return val


stack_object = AddingStack()

for i in range(5):
    stack_object.push(i)
print(stack_object.get_sum())

for i in range(5):
    print(stack_object.pop())

代码有效。作为使用 class AddingStack(Stack) 的解释,它说:

We don't want to modify the previously defined stack. It's already good enough in its applications, and we don't want it changed in any way. We want a new stack with new capabilities. In other words, we want to construct a subclass of the already existing Stack class.

The first step is easy: just define a new subclass pointing to the class which will be used as the superclass.

This is what it looks like: class AddingStack(Stack): pass

The class doesn't define any new component yet, but that doesn't mean that it's empty. It gets all the components defined by its superclass

但是,当我运行同样的代码,只是修改了这行:

class AddingStack():

它仍然有效。我不明白 class AddingStack(Stack) 的好处是什么?

However, when I run the same code, but just modify the line to:

class AddingStack():

it still works. I don't understand what the benefit of class AddingStack(Stack) is?

它仍然有效,因为 AddingStack 中的方法显式调用了 Stack 中的其他方法。

您实际上并没有使用任何继承的方法,这破坏了整个继承点。

通常 OOP 中 继承 的好处是能够从现有的 class 中创建 class,并对其进行修改 有点轻松。

如果你真的只是覆盖super-class中的每一个函数,那么不,不要使用继承,对你没有任何好处。

当你有一个 sub-class 时,它非常有用,它只改变了 super 的一些功能和东西-class,其余的将使用 super-class 函数。

之所以有效,是因为您在计算总和时并未实际使用堆栈的元素,而是将结果累加到 __sum 变量中。

您也没有使用继承,而是委托给 class Stack.

pop()push() 方法

练习的objective好像是让你把栈的元素加起来(在superclass里已经实现了),实现get_sum()这样的您遍历堆栈上的值列表并将它们相加。