gpt4 book ai didi

python - 导入先前初​​始化的对象 (Python)

转载 作者:太空宇宙 更新时间:2023-11-04 05:05:15 24 4
gpt4 key购买 nike

我正在创建我的第一个 python 包。

__init__.py , 我导入并打开一个对象 App来自模块。

from app import App
app = App()

app.py :

class App(tk.Tk):

def __init__(self):
#Create App
tk.Tk.__init__(self)
self.geometry("1000x550")
self.title("Game")
self.container = tk.Frame(self).grid()

然后,在另一个模块中game.py , 我需要访问 appapp.containerapp 时创建在 __init__.py 中初始化.

我试过:

from app import App
# Does not retrieve variables

from __init__ import app
# Does not retrieve object

from app import App
app = App()
# Intialized the object twice

最佳答案

您不应该在 __init__.py 文件中创建 App 的实例。包应该只提供对象的定义。当然也有异常(exception),但刚开始时您不应该这样做。

你的 __init__.py 文件应该只有这个:

from app import App

假设它位于名为“mypackage”的文件夹中,在任何需要应用程序的地方,您都可以:

from mypackage import App
app = App()

关于python - 导入先前初​​始化的对象 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44680705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com