簡體   English   中英

從導入的模塊重新定義被調用的函數

[英]Redefining a called function from an imported module

所以例如我有 mod1.py:

def foo():
    bar()

def bar():
    print("This is bar in mod1")

還有一個 mod2.py:

from mod1 import *

def bar():
    print("This is bar in mod2")

然后是 mod3.py:

import mod1
import mod2

mod1.foo()
mod2.foo()

運行 mod3.py 后,我得到相同的輸出:“This is bar in mod1”,即使我在 mod2.py 中重新定義了它。

據我了解,當我在 mod2 中調用 foo 時,它會在 mod1 中查找它,因為我導入了它並且沒有重新定義它。

有什么方法可以讓 foo 在 mod2 而不是 mod1 中查找 bar 嗎?

Ofc 無需將 foo 復制到 mod2 或在 mod1 中接觸 foo 或 bar 並且能夠在 mod3 中調用它們,如 mod3.py 示例中那樣通過它們的命名空間進行區分。

難度不大,直接在bar傳過去就行了。

仔細閱讀問題后,這是禁止的,因為無法觸及mod1.py。 哦,好吧,還是留下吧。

模塊1.py

def bar():
    print("This is bar in mod1")

def foo(bar=bar):
    bar()

mod2.py 不變

模塊3.py

import mod1
import mod2

mod1.foo()
mod2.foo()
mod2.foo(mod2.bar)

輸出:

This is bar in mod1
This is bar in mod1
This is bar in mod2

更新:不接觸 mod1 的源代碼

Monkeypatching,或多或少。 線程安全? 可能不是。

import mod1
import mod2

mod1.foo()

ori_bar = mod1.bar

# I think this would be a good place for a context manager rather than 
# finally which needs adjustments to handle exceptions
try:
    mod1.bar = mod2.bar
    mod2.foo()
finally:
    mod1.bar = ori_bar

mod1.foo()

輸出:

This is bar in mod1
This is bar in mod2
This is bar in mod1

術語方面,原始的foo實現會被視為閉包嗎? 因為我相信這種特定行為在 Python 中已經存在很長時間了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM