抽象类

 1 from abc import ABCMeta, abstractmethod
 2 
 3 class Super(object):
 4     __metaclass__ = ABCMeta
 5 
 6     def delegate(self):
 7         self.action()
 8 
 9     @abstractmethod
10     def action(self):
11         pass
12 
13     @abstractmethod
14     def method(self):
15         pass

使用metaclass与@abstractmethod定义python抽象类

现在 Super() 是个抽象类,如果尝试实例化 Super 类:

x = Super()

会引发:TypeError: Can't instantiate abstract class Super with abstract methods action, method

继承 Super 类,实现 action, method 方法。

 1 class Sub(Super):
 2     def action(self):
 3         print 'spam'
 4 
 5     def method(self):
 6         print 'method'
 7 
 8 if __name__ == '__main__':
 9     x = Sub()
10     x.delegate()
11     x.method()

运行结果:
>>>
spam
method

 

 

 

posted @ 2013-08-04 02:11  Roger|  阅读(188)  评论(0编辑  收藏  举报