gpt4 book ai didi

python - 在 Python 中,通过类实例化导入两次?

转载 作者:太空狗 更新时间:2023-10-30 00:28:08 26 4
gpt4 key购买 nike

models.py 我有:

...
db = SQLAlchemy(app)

class User(db.Document):
...

在我的应用程序中,serve.pymodels.py 调用:

from models import User 

双重导入是否会两次实例化数据库并可能导致问题?

最佳答案

Is that double import going to instantiate the db twice and potentially cause a problem?

不,不会。导入模块后,无论通过 import 语句进行任何进一步导入,它仍然可用。

导入后,模块存储在 sys.modules 中。

如果你想重新加载模块,你必须使用reload(module)

示例: bar.py

xs = [1, 2, 3]

导入两次:

>>> from bar import xs
>>> id(xs)
140211778767256
>>> import bar
>>> id(bar.xs)
140211778767256

注意到身份是相同的了吗?

缓存:

>>> import sys
>>> sys.modules["bar"] is bar
True

关于python - 在 Python 中,通过类实例化导入两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20609500/

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