[英]how to create top-level module function from another function?
給定一個帶有__init__.py
文件的模塊mymodule
,我如何從該文件中的另一個 function 定義 mymodule 的函數?
__init__.py
代碼大綱:
def a():
THISMODULE.__dict__["b"] = lambda: print("this is not weird")
a()
b() # Expect "this is not weird" output
mymodule
是anothermodule
的替代品,我想讓代碼更改像用import mymodule as thething
import anothermodule as thething
簡單。 由於我還沒有實現anothermodule
的所有功能,我想向用戶發送有關它的通知,而不是因“未定義”而崩潰。
__name__
是由導入機制設置的模塊屬性,其計算結果為當前模塊的名稱。 將此添加到文件的頂部:
import sys
THISMODULE = sys.modules[__name__]
並且您已經擁有的 rest 應該可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.