如何重新定义我在python中导入的函数使用的函数?

bou*_*472 2 python decorator python-import python-3.x

我导入一些模块Foo并使用Foo该模块中定义的类.该类具有f调用g该模块Foo本身导入的另一个函数的函数module_with_g.我想在实例化时重新定义gf用法的定义Foo.这里有3个文件显示了这种情况.

Foo.py

from module_with_g import g

class Foo:
    def f(self):
        x = 'bar'
        g(x)
Run Code Online (Sandbox Code Playgroud)

module_with_g.py

def g(x):
    print(x + x)
Run Code Online (Sandbox Code Playgroud)

module_with_modified_Foo_f.py

import Foo

def new_g(x):
    print(x + x + x)

if __name__ == '__main__':
    foo =  Foo.Foo()
    foo.f()
Run Code Online (Sandbox Code Playgroud)

运行最后一个脚本给出barbar.我想要的是让我们foo.f使用自己的功能而不是它g,我希望得到它barbarbar.

我自己的尝试是尝试使用装饰器以某种方式重新定义foo.f,但我没有任何运气.

module_with_modified_Foo_f.py

import Foo

def new_g(x):
    print(x + x + x)

def redefine_f(f):
    def redefined_f(*args, **kwargs):
        return f(*args, **kwargs)
    #redefined_f.g = new_g
    return redefined_f

if __name__ == '__main__':
    foo =  Foo.Foo()
    # foo.f = redefine_f(foo.f)
    # foo.__dict__['g'] = new_g # another approach
    foo.f()
Run Code Online (Sandbox Code Playgroud)

Alo*_*kur 5

我可以做到这一点,我已经修改了如Foo.g = new_gmodule_with_modified_Foo_f.py

import Foo
def new_g(x):
    print(x + x + x)
Foo.g = new_g
if __name__ == '__main__':
    foo =  Foo.Foo()
    foo.f()
Run Code Online (Sandbox Code Playgroud)

我得到了结果 - barbarbar