【问题标题】:How can I override class call inside of an imported class in python?如何在 python 中的导入类中覆盖类调用?
【发布时间】:2015-06-22 14:24:31
【问题描述】:

假设我在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 方法。

但是如何在调用者modul2 中使用IN 类覆盖导入的C 类中modul1 的IN 类的任何调用?
我想更改原始IN 类的一些功能。我希望C 类在行中调用

cl = IN()

我自己的 IN() 具有更改功能的类。

【问题讨论】:

标签: python class inheritance


【解决方案1】:

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 构造函数是如何被调用的。

【讨论】:

  • 您能否解释一下为什么如果我对module2.py 进行以下简单更改,您将不再覆盖该类?将import module1 更改为from module1 import IN,C 并将class IN 的名称更改为class IN2 然后将module1.IN = IN2 更改为IN = IN2
猜你喜欢
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 2022-09-30
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多