由于python 没有抽象类、接口的概念,所以要实现这种功能得abc.py 这个类库,具体方式如下
1 from abc import ABCMeta, abstractmethod 2 3 #抽象类 4 class Headers(object): 5 __metaclass__ = ABCMeta 6 7 def __init__(self): 8 self.headers = '' 9 10 @abstractmethod 11 def _getBaiduHeaders(self):pass 12 13 def __str__(self): 14 return str(self.headers) 15 16 def __repr__(self): 17 return repr(self.headers) 18 19 #实现类 20 class BaiduHeaders(Headers): 21 def __init__(self, url, username, password): 22 self.url = url 23 self.headers = self._getBaiduHeaders(username, password) 24 25 def _getBaiduHeaders(self, username, password): 26 client = GLOBAL_SUDS_CLIENT.Client(self.url) 27 headers = client.factory.create('ns0:AuthHeader') 28 headers.username = username 29 headers.password = password 30 headers.token = _baidu_headers['token'] 31 return headers
如果子类不实现父类的_getBaiduHeaders方法,则抛出TypeError: Can't instantiate abstract class BaiduHeaders with abstract methods 异常