[英]Python - how can I override the functionality of a class before it's imported by a different module?
[英]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类进口的内部C
类IN
类来电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.