Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Method replacement for object instance</strong></p> <p>You can replace methods of already created object instances. It allows you to create object instance with different (exceptional) functionality:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def fun(self): ... print "C.a", self ... &gt;&gt;&gt; inst = C() &gt;&gt;&gt; inst.fun() # C.a method is executed C.a &lt;__main__.C object at 0x00AE74D0&gt; &gt;&gt;&gt; instancemethod = type(C.fun) &gt;&gt;&gt; &gt;&gt;&gt; def fun2(self): ... print "fun2", self ... &gt;&gt;&gt; inst.fun = instancemethod(fun2, inst, C) # Now we are replace C.a by fun2 &gt;&gt;&gt; inst.fun() # ... and fun2 is executed fun2 &lt;__main__.C object at 0x00AE74D0&gt; </code></pre> <p>As we can <code>C.a</code> was replaced by <code>fun2()</code> in <code>inst</code> instance (<code>self</code> didn't change).</p> <p>Alternatively we may use <code>new</code> module, but it's depreciated since Python 2.6:</p> <pre><code>&gt;&gt;&gt; def fun3(self): ... print "fun3", self ... &gt;&gt;&gt; import new &gt;&gt;&gt; inst.fun = new.instancemethod(fun3, inst, C) &gt;&gt;&gt; inst.fun() fun3 &lt;__main__.C object at 0x00AE74D0&gt; </code></pre> <p><strong>Node:</strong> This solution shouldn't be used as general replacement of inheritance mechanism! But it may be very handy in some specific situations (debugging, mocking).</p> <p><strong>Warning:</strong> This solution will not work for built-in types and for new style classes using slots.</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