1

Let say I have the following script in modul1:

class IN(object):
    def __init__(self):
        pass

class C(object):
    def __init__(self, x):
        pass

    def func(self):
        cl = IN()

Then I want to use C class inside another script:

from modul1 import C 

class IN(object):
    def __init__(self):
        pass

class C2(C):
    def __init__(self, x):
        C.__init__(self, x)

I can override C class's func method by creating a method with the same name in C2 class.

But how can I override any call of modul1's IN class inside of imported C class with IN class in the caller modul2?
I want to change some functionality of original IN class. I want C class to call in the row

cl = IN()

my own IN() class with the altered functionality.

Geeocode
  • 5,705
  • 3
  • 20
  • 34

1 Answers1

0

module1.py:

class IN(object):
    def __init__(self):
        print "i am the original IN"

class C(object):
    def __init__(self, x):
        pass

    def func(self):
        print "going to create IN from C's func"
        cl = IN()

module2.py:

import module1

class IN(object):
    def __init__(self):
        print "I am the new IN"

class C2(module1.C):
    def __init__(self, x):
        super(C2, self).__init__(x)


print "\n===Before monkey patching==="
C2(1).func()
#monkey patching old In with new In
module1.IN = IN
print "\n===After monkey patching==="
C2(1).func()

Output while running the script module2.py:

===Before monkey patching===
going to create IN from C's func
i am the original IN

===After monkey patching===
going to create IN from C's func
I am the new IN

You can see how the module2's In constructor is being called.

Kavin Eswaramoorthy
  • 1,595
  • 11
  • 19
  • Could you please explain why If I make the following simple change to `module2.py` you no longer override the class? Change `import module1` to `from module1 import IN,C` and change the name of `class IN` to `class IN2` then change `module1.IN = IN2` to `IN = IN2` – Pete Mar 07 '16 at 11:27