English 中文(简体)
Making super() work in Python s urllib2.Request
原标题:

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
最佳回答

This should work fine since the hierarchy is simple

class ExtendedRequest(urllib2.Request):
    def __init__(self,...):
        urllib2.Request.__init__(self,...)
问题回答

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.

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




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签