Python - how can I override class functionality before importing another module?

I have a class that is imported into module_x to instantiate, but first I want to override one of the class methods to dynamically enable a specific function (inside some middleware that runs before module_x ).

+6
python
source share
3 answers

Neither AndiDog nor Andrew will answer your question completely. But they provided the most important tools to solve your problem (+1 for both). I will use one of my suggestions in my answer:

You will need 3 files:

File 1: myClass.py

 class C: def func(self): #do something 

File 2: importer.py

 from myClass import * def changeFunc(): A = C() A.func = lambda : "I like pi" return A if __name__ == "importer": A = changeFunc() 

File 3: module_x.py

 from importer import * print A.func() 

Module_x output will print "I like pi"

Hope this helps

+1
source share

You should be aware that every type of class (e.g. C in class C: ... ) is an object, so you can simply overwrite class methods. As long as the instances do not overwrite their own methods (this will not happen too often, because it is not very useful for single innervations), each instance uses methods inherited from its class type. That way, you can even replace the method after creating the instance.

For example:

 class C: def m(self): print "original" c1 = C() c1.m() # prints "original" def replacement(self): print "replaced!" Cm = replacement c1.m() # prints "replaced!" C().m() # prints "replaced!" 
+2
source share

Since each python class is actually a dictionary (and not just objects!)
You can easily override class methods by associating them with a new function.

 class A: def f(self): return 5 a = A() af() #5 Af = lambda self: 10 af() #10 

You must use it with caution. In most cases, decorators and the right OO design will work for you, and if you are forced to override a class method, you may have done something wrong.

+1
source share

All Articles