开发者

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

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 开发者_如何学Cinclude a specific feature dynamically (inside some middleware that runs before module_x is loaded.


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


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!"


Since every python class is actually a dictionary (not only objects!)
You can easily override class methods by associate them with new function.

class A:
    def f(self):
        return 5

a = A()
a.f() #5

A.f = lambda self: 10
a.f() #10

You should use it with care. In most cases decorators & proper OO-design will work for you and if you forced to override class method, maybe, you make something wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜