Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how can I override the functionality of a class before it's imported by a different module?

Tags:

python

I have a class that's being imported in module_x for instantiation, but first I want to override one of the class's methods to include a specific feature dynamically (inside some middleware that runs before module_x is loaded.

like image 415
orokusaki Avatar asked Sep 25 '10 18:09

orokusaki


People also ask

How do you override a class in Python?

In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.

Can we override a method within the same class in Python?

Therefore, you cannot override two methods that exist in the same class, you can just overload them.

Can you override a function in Python?

Method overriding in Python is when you have two methods with the same name that each perform different tasks. This is an important feature of inheritance in Python. In method overriding, the child class can change its functions that are defined by its ancestral classes.


2 Answers

Neither AndiDog's nor Andrew's answer answer your question completely. But they have given the most important tools to be able to solve your problem (+1 to both). I will be using one of their 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()

The output of module_x would print "I like pi"

Hope this helps

like image 79
inspectorG4dget Avatar answered Sep 29 '22 13:09

inspectorG4dget


You should know that each class type (like C in class C: ...) is an object, so you can simply overwrite the class methods. As long as instances don't overwrite their own methods (won't happen too often because that's not really useful for single inntances), each instance uses the methods as inherited from its class type. This way, you can even replace a method after an instance has been created.

For example:

class C:
    def m(self):
        print "original"

c1 = C()
c1.m() # prints "original"

def replacement(self):
    print "replaced!"

C.m = replacement

c1.m() # prints "replaced!"
C().m() # prints "replaced!"
like image 31
AndiDog Avatar answered Sep 29 '22 13:09

AndiDog