代码之家  ›  专栏  ›  技术社区  ›  Boldewyn

使super()在python的urllib2.request中工作

  •  1
  • Boldewyn  · 技术社区  · 15 年前

    今天下午,我花了几个小时试图在我的自定义扩展中找到一个bug。 urllib2.Request . 我发现问题在于 super(ExtendedRequest, self) ,因为 请求请求 是(我在python 2.5上)还是一个旧样式的类,在那里使用 super() 不可能。

    创建具有这两个特性的新类的最明显的方法,

    class ExtendedRequest(object, urllib2.Request):
        def __init__():
            super(ExtendedRequest, self).__init__(...)
    

    不起作用。打电话给它,我就只能 AttributeError: type 由提出 urllib2.Request.__getattr__() . 现在,在我开始复制粘贴整个 请求请求 从/usr/lib/python类,将其重写为

    class Request(object):
    

    有没有人知道,我如何才能以更优雅的方式实现这一点?用 有一个 新式 基于类 请求请求 有工作支持 超级() )

    编辑: 顺便说一下:属性错误提到:

    >>> class ExtendedRequest(object, urllib2.Request):
    ...   def __init__(self):
    ...     super(ExtendedRequest, self).__init__('http://stackoverflow.com')
    ...
    >>> ABC = ExtendedRequest ()
    >>> d = urllib2.urlopen(ABC)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/python2.5/urllib2.py", line 124, in urlopen
        return _opener.open(url, data)
      File "/usr/lib/python2.5/urllib2.py", line 373, in open
        protocol = req.get_type()
      File "/usr/lib/python2.5/urllib2.py", line 241, in get_type
        if self.type is None:
      File "/usr/lib/python2.5/urllib2.py", line 218, in __getattr__
        raise AttributeError, attr
    AttributeError: type
    
    3 回复  |  直到 15 年前
        1
  •  1
  •   John La Rooy    15 年前

    class ExtendedRequest(urllib2.Request):
        def __init__(self,...):
            urllib2.Request.__init__(self,...)
    
        2
  •  1
  •   unutbu    15 年前
        3
  •  0
  •   Ehsan Foroughi    15 年前

    class ExtendedRequest(object, urllib2.Request):
        def __init__(self):
            super(ExtendedRequest, self).__init__(self)
    

    >>> x = ExtendedRequest()
    >>> super(ExtendedRequest, x)
    <super: <class 'ExtendedRequest'>, <ExtendedRequest object>>
    
    推荐文章