Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <code>super</code>, as follows:</p> <pre><code>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())() </code></pre> <p>etc.</p> <p>Now, alternatives ARE possible, since a Python object can change its own <code>__class__</code>, 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;-).</p> <p><strong>Edit</strong>: the extra injection of <code>object</code> 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...:</p> <pre><code>&gt;&gt;&gt; import httplib &gt;&gt;&gt; class Z(object): pass ... &gt;&gt;&gt; class Y(Z, httplib.HTTPConnection): pass ... &gt;&gt;&gt; Y.mro() [&lt;class '__main__.Y'&gt;, &lt;class '__main__.Z'&gt;, &lt;type 'object'&gt;, &lt;class httplib.HTTPConnection at 0x264ae0&gt;] &gt;&gt;&gt; class X(Z, httplib.HTTPConnection, object): pass ... &gt;&gt;&gt; X.mro() [&lt;class '__main__.X'&gt;, &lt;class '__main__.Z'&gt;, &lt;class httplib.HTTPConnection at 0x264ae0&gt;, &lt;type 'object'&gt;] &gt;&gt;&gt; </code></pre> <p>The method-resolution order (aka MRO) in class Y (without the further injection of an <code>object</code> base) has object before the class from httplib (so <code>super</code> 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!-)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload