As per my comment on @Mark's answer, I like the factory approach he's advocating. However, I wouldn't do it exactly his way, because he makes a new class afresh every time. Rather, this is a nice use case for mixin MI and super
, as follows:
class MyConnectionPlugin(object):
def __init__(self, *args, **kw):
super(MyConnectionPlugin, self).__init__(*args, **kw)
# etc etc -- rest of initiatizations, other methods
class SecureConnection(MyConnectionPlugin,
httplib.HTTPSConnection, object):
pass
class PlainConnection(MyConnectionPlugin,
httplib.HTTPConnection, object):
pass
def ConnectionClass(secure):
if secure:
return SecureConnection
else:
return PlainConnection
conn = ConnectionClass(whatever_expression())()
etc.
Now, alternatives ARE possible, since a Python object can change its own __class__
, and so forth. However, like shooting flies with a rhino rifle, using excessive force (extremely powerful, deep, and near-magical language features) to solve problems that can be nicely solved with reasonable restraint (the equivalent of a flyswatter), is NOT recommended;-).
Edit: the extra injection of object
in the bases is needed only to compensate for the sad fact that in Python 2.* the HTTPConnection class is old-style and therefore doesn't play well with others -- witness...:
>>> import httplib
>>> class Z(object): pass
...
>>> class Y(Z, httplib.HTTPConnection): pass
...
>>> Y.mro()
[<class '__main__.Y'>, <class '__main__.Z'>, <type 'object'>, <class httplib.HTTPConnection at 0x264ae0>]
>>> class X(Z, httplib.HTTPConnection, object): pass
...
>>> X.mro()
[<class '__main__.X'>, <class '__main__.Z'>, <class httplib.HTTPConnection at 0x264ae0>, <type 'object'>]
>>>
The method-resolution order (aka MRO) in class Y (without the further injection of an object
base) has object before the class from httplib (so super
doesn't do the right thing), but the extra injection jiggles the MRO to compensate. Alas, such care is needed in Python 2.* when dealing with bad old legacy-style classes; fortunately, in Python 3, the legacy style has disappeared and every class "plays well with others" as it should!-)