由于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 @abstractmethod11 def _getBaiduHeaders(self):pass12 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 = url23 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 = username29 headers.password = password30 headers.token = _baidu_headers['token']31 return headers
如果子类不实现父类的_getBaiduHeaders方法,则抛出TypeError: Can't instantiate abstract class BaiduHeaders with abstract methods 异常