繁体   English   中英

如何覆盖python中导入的类中的类调用?

[英]How can I override class call inside of an imported class in python?

假设我在modul1有以下脚本:

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

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

    def func(self):
        cl = IN()

然后我想在另一个脚本中使用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方法。

但我怎么能覆盖的任何呼叫modul1的IN类进口的内部CIN类来电modul2
我想更改原始IN类的某些功能。 我想让C类在行中调用

cl = IN()

我自己的IN()类,其功能已更改。

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

运行脚本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构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM