Question

Is there any reason python's BaseHTTPServer.HTTPServer is an old-style class?

>>> import BaseHTTPServer
>>> type(BaseHTTPServer.HTTPServer)
classobj

I ask because I want to use super in a class that inherits from HTTPServer and can't. There is a workaround:

class MyHTTPServer(HTTPServer,object):
    ...

Does this workaround have any hidden 'gotchas'?

Était-ce utile?

La solution

According to Steve Holden,

... it was easier to leave them as they were than risk
introducing incompatibilities.

The problem was corrected in Python3, where all classes are new-style classes.


Nowadays, we see only the advantages of new-style classes, and we are accustomed to programming in ways that are compatible with new-style. However, back when classic classes were the norm, there could have been code like this:

def __str__():
    return "I'm Classic"

class Classic: pass

c = Classic()
c.__str__ = __str__
print(c)

which prints

I'm Classic

However, if the classic class were changed to be new-style, then this method of defining special methods on instances would be broken:

class New(object): pass
n = New()
n.__str__ = __str__
print(n)

prints

<__main__.New object at 0xb746ad4c>

With new-style classes, special methods such as __str__ must be defined in the class (or in the MRO) of the object for it to affect the object. That is not the case with old-style classes.

Since Python2 is intended to be backwards-compatible, differences such as this prevent Python2 from changing classic classes in the standard lib to new-style.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top