Python中的抽象超类

 1 # -*- coding:utf-8 -*-
 2 class Super(object):
 3     
 4     def test(self):
 5         self.action()
 6 
 7 class Sub(Super):
 8     
 9     def action(self):
10         print "sub action"
11         
12 obj=Sub()
13 obj.test()

代码中,超类Super中定义了一个函数test。调用了自身的action函数。但是Super中并没有定义action函数。

这是为什么?

----------------------------------

在这个例子中的超类,有时会叫做抽象超类。意思是说,类的部分行为由子类来提供。如果预期的方法没有在子类中有定义,那么会抛出没有定义变量名的异常。

----------------------------------

这就是为什么上面代码的输出是

sub action

-------------------------------------

为了避免子类忘记实现action函数,在Super类中,也可以加上action函数,并使用assert来提示用户必须覆盖这个函数。

代码如下:

class Super(object):
    
    def test(self):
        self.action()
    def action(self):
        assert False,"action must be implemented!"

当然,也可以在Super中使用抛出异常的方法来实现这个提示子类覆盖action函数的功能。

代码如下:

class Super(object):
    
    def test(self):
        self.action()
    def action(self):
        raise NotImplementedError("action must be implemented!")
原文地址:https://www.cnblogs.com/liyiran/p/4207842.html