如何覆盖在python中的导入类中的类调用? [英] How can I override class call inside of an imported class in python?

查看:114
本文介绍了如何覆盖在python中的导入类中的类调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 modul1 中有以下脚本:

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()


$ b b

然后我要在另一个脚本中使用 C 类:

from modul1 import C 

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

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

我可以通过在 C2 类中创建同名的方法来覆盖 C 类的func方法。

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

但是如何重写 modul1 的I​​N类里面的任何调用 C IN 类中的调用 modul2

我想改变原始 IN 类的一些功能。我要 C 类调用

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()

我自己的 IN修改的功能。

my own IN() class with the altered functionality.

推荐答案

module1.py:

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:

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()

在运行脚本module2.py时输出:

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

你可以看到如何调用module2的In构造函数。

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

这篇关于如何覆盖在python中的导入类中的类调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆