【3.2】抽象基类(abc模块)
实现一个抽象基类,不适用abc模块
1 class Base: 2 def get(self, key): 3 raise NotImplemented 4 5 def set(self, key, value): 6 raise NotImplemented 7 8 9 class Test(Base): 10 def get(self, key): 11 return key 12 13 14 test = Test() 15 print(test.get('key'))
当没有实现抽象基类的方法的时候,会抛出异常,但是会有一个缺点,只有在调用方法的时候,才会抛出异常
实现一个抽象基类,使用abc模块
1 import abc 2 3 4 class Base(metaclass=abc.ABCMeta): 5 @abc.abstractmethod 6 def get(self, key): 7 raise NotImplemented 8 9 @abc.abstractmethod 10 def set(self, key, value): 11 raise NotImplemented 12 13 14 class Test(Base): 15 def get(self, key): 16 return key 17 18 def set(self, key, value): 19 return key, value 20 21 22 test = Test() 23 print(test.get('key')) 24 print(test.set('key', 'value'))