让 super() 在 Python 的 urllib2.Request 中工作

发布于 2024-08-21 19:02:03 字数 1532 浏览 7 评论 0原文

今天下午,我花了几个小时试图在 urllib2.Request 的自定义扩展中找到错误。正如我发现的那样,问题是 super(ExtendedRequest, self) 的使用,因为 urllib2.Request (我使用的是 Python 2.5)仍然是旧样式类,其中不可能使用 super()

创建具有这两种功能的新类的最明显方法

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

是行不通的。调用它,我留下了由 urllib2.Request.__getattr__() 引发的 AttributeError: type 。现在,在我开始复制并粘贴 /usr/lib/python 中的整个 urllib2.Request 类之前,只是为了像

class Request(object):

任何人的想法一样重写它,我如何以更优雅的方式实现这一点? (这个是有一个基于urllib2.Request新式类,并支持super().)

编辑:顺便说一句:AttributeError 提到:

>>> 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

This afternoon I spent several hours trying to find a bug in my custom extension to urllib2.Request. The problem was, as I found out, the usage of super(ExtendedRequest, self), since urllib2.Request is (I'm on Python 2.5) still an old style class, where the use of super() is not possible.

The most obvious way to create a new class with both features,

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

doesn't work. Calling it, I'm left with AttributeError: type raised by urllib2.Request.__getattr__(). Now, before I start and copy'n paste the whole urllib2.Request class from /usr/lib/python just to rewrite it as

class Request(object):

has anyone an idea, how I could achieve this in a more elegant way? (With this being to have a new-style class based on urllib2.Request with working support for super().)

Edit: By the way: the AttributeError mentioned:

>>> 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

椒妓 2024-08-28 19:02:03

这应该可以正常工作,因为层次结构很简单

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

This should work fine since the hierarchy is simple

class ExtendedRequest(urllib2.Request):
    def __init__(self,...):
        urllib2.Request.__init__(self,...)
-小熊_ 2024-08-28 19:02:03

使用 super 可能并不总是最佳实践。使用super有很多困难。请阅读 James Knight 的 http://fuhm.org/super-harmful/ 的示例。

该链接显示(除其他问题外)

  1. 如果子类使用 super,则超类必须使用 super
  2. 所有使用 super 的子类的 __init__ 签名应该匹配。您必须将收到的所有参数传递给 super 函数。您的 __init__ 必须准备好调用层次结构中任何其他类的 __init__ 方法。
  3. 切勿在 __init__ 中使用位置参数

在您的情况下,上述每个标准都被违反。

詹姆斯·奈特还说,

super() 的唯一情况
实际上可以有帮助的是当你
拥有钻石传承。甚至
那么,它通常不如
你可能已经想到了。

正确使用 super 的条件非常繁琐,我认为 super 的用处相当有限。与子类化相比,更喜欢组合设计模式。如果可以的话,避免钻石继承。如果您从上(对象)到下控制对象层次结构,并一致地使用 super,那么就可以了。但由于在这种情况下您无法控制整个类层次结构,因此我建议您放弃使用 super

Using super may not always be the best-practice. There are many difficulties with using super. Read James Knight's http://fuhm.org/super-harmful/ for examples.

That link shows (among other issues) that


  1. Superclasses must use super if their subclasses do
  2. The __init__ signatures of all subclasses that use super should match. You must pass all arguments you receive on to the super function. Your __init__ must be prepared to call any other class's __init__ method in the hierarchy.
  3. Never use positional arguments in __init__

In your situation, each of the above critera is violated.

James Knight also says,

The only situation in which super()
can actually be helpful is when you
have diamond inheritance. And even
then, it is often not as helpful as
you might have thought.

The conditions under which super can be used correctly are sufficiently onerous, that I think super's usefulness is rather limited. Prefer the Composition design pattern over subclassing. Avoid diamond inheritance if you can. If you control the object hierarchy from top (object) to bottom, and use super consistently, then you are okay. But since you don't control the entire class hierarchy in this case, I'd suggest you abandon using super.

婴鹅 2024-08-28 19:02:03

我认为您错过了将 self 参数传递给示例中 init 的定义。
试试这个:

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

我测试了它,它似乎工作正常:

>>> x = ExtendedRequest()
>>> super(ExtendedRequest, x)
<super: <class 'ExtendedRequest'>, <ExtendedRequest object>>

I think you missed to pass the self parameter to definition of init in your sample.
Try this one:

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

I tested it and it seems to work okey:

>>> x = ExtendedRequest()
>>> super(ExtendedRequest, x)
<super: <class 'ExtendedRequest'>, <ExtendedRequest object>>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文