[英]How do I reach an object in a parent module from a class in a child module in Python?
我有兩個相關文件。 一個/main.py
和一個/a/b.py
。
/main.py
進口/a/b.py
:
...
bot = interactions.Client() # the object I want in b.py
importlib.import_module("a.b")
...
/a/b.py:
class Command:
def __init__(self):
self.var = "foo"
@bot.decorator() # bot is undefined currently
def dec_func(self, args):
# do things
我試過了...
bot
object 存儲在文件中並將其加載到b.py
,但我不確定這是否是一個可行的解決方案。 我可能不得不使用 dill,因為 pickle 給了我一個weakref
錯誤Command()
包裝在另一個Parent
class 中,並讓Parent
在__init__()
中接收bot
object 以便子 class 可以訪問它class Parent:
global bot
def __init__(self, bot: interactions.Client):
self.bot = bot
class Command:
@bot # returns: undefined
...
from main import bot
in b.py
,但這不起作用,因為這將復制已經運行main.py
啟動的事件循環(除非我可以添加一個if __name__ == "__main__"
檢查?)main.py
包裝在 function 中,進行__name__ == "__main__"
檢查,從b.py
導入main
,但后來我想我在一個實例迷宮中很深,因為返回bot is not defined
我如何訪問bot
?
為此,顯然將bot = interactions.Client
移動到單獨的bot.py
並在需要時讓我的模塊和main.py
導入bot.bot
就足夠了
main.py
from bot import bot
from a import b
# do things with b
bot.start()
a/b.py
from bot import bot
@bot.decorator
async def foo():
....
bot.py
bot = interactions.Client()
那行得通
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.