Welcome, guest | Sign In | My Account | Store | Cart

Once in a while it becomes necessary to globally change the behaviour of classes in a third party library. This code demonstrates the ability to modify the __init__ method of an arbitrary class in-place. It's also good for making functional programmers wince, which can be entertaining :-)

Python, 25 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from __future__ import nested_scopes
import new


def enhance__init__(klass, f):
    ki = klass.__init__
    klass.__init__ = new.instancemethod(
        lambda *args, **kwds: f(ki, *args, **kwds),None,klass)


def demo():
    class X:
        def __init__(self,v):
            self.v = v

    def g(__init__, self, v):
        __init__(self, v)
        self.parrot='dead'

    enhance__init__(X, g)

    x = X(2)
    print x.parrot

demo()