zoukankan      html  css  js  c++  java
  • python 抽象类、抽象方法的实现

    由于python 没有抽象类、接口的概念,所以要实现这种功能得abc.py 这个类库,具体方式如下

    from abc import ABCMeta, abstractmethod
    
    #抽象类
    class Headers(object):
        __metaclass__ = ABCMeta
    
        def __init__(self):
            self.headers = ''
    
        @abstractmethod
        def _getBaiduHeaders(self):pass
    
        def __str__(self):
            return str(self.headers)
    
        def __repr__(self):
            return repr(self.headers)
    
    #实现类
    class BaiduHeaders(Headers):
        def __init__(self, url, username, password):
            self.url = url
            self.headers = self._getBaiduHeaders(username, password)
    
        def _getBaiduHeaders(self, username, password):
            client = GLOBAL_SUDS_CLIENT.Client(self.url)
            headers = client.factory.create('ns0:AuthHeader')
            headers.username = username
            headers.password = password
            headers.token = _baidu_headers['token']
            return headers
    

    如果子类不实现父类的_getBaiduHeaders方法,则抛出TypeError: Can't instantiate abstract class BaiduHeaders with abstract methods  异常

  • 相关阅读:
    字典与集合
    gitee
    在使用pycharm时同时缩进、左移、多行注释
    代码1(while循环和IF条件语句,字符格式化,break,continue)
    python基础-工具
    11 Serializer组件
    10 响应模块
    09 异常模块
    08 解析模块
    07 渲染模块
  • 原文地址:https://www.cnblogs.com/Vito2008/p/4974802.html
Copyright © 2011-2022 走看看