![](/img/trans.png)
[英]A function is being called from a module, before the module was imported
[英]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。 哦,好吧,還是留下吧。
def bar():
print("This is bar in mod1")
def foo(bar=bar):
bar()
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
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.