如何替换导入库中的导入?
假设我们有3个文件:
library1.py:
SomeVariable = '1'
library2.py:
import library1
print(library1.SomeVariable)
library3.py:
SomeVariable = '2'
我的目标是“更改” library1 import(不仅是1个变量),因此结果输出将为'2' (换句话说,替换Library1中的Library1的缓存2.Py中的Library3)
Suppose, we have 3 files:
library1.py:
SomeVariable = '1'
library2.py:
import library1
print(library1.SomeVariable)
library3.py:
SomeVariable = '2'
my goal is to "change" library1 import(not only 1 variable) in library2.py so result output will be '2'
(in other words,replace cache of library1 in library2.py to library3)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
警告:此方法是非常 hacky的,您的
可能会破坏东西。假设我们有此
library1.py
:并且,我们想用
oferwrite.py.py
:如果我们进入shell,我们可以看到一个模块有一个
__ dict __
属性将其包含在其中的所有内容。这很好,因为我们可以使用它来访问属性而无需真正访问它们:
我们不想覆盖任何魔法(以两个下划线启动和结束)属性,因此:
我们也不想覆盖任何内置功能:
这就是所有这些聚集在一起的地方。
我们在
Library3
中使用值来覆盖__ dict __
library1
的。您可以看到
library1
已被覆盖:WARNING: This method is very hacky, and you
mightprobably will break things.Let's say we have this
library1.py
:And, we want to overwrite it with
overwrite.py
:If we go into a shell, we can see that a module has a
__dict__
attribute that holds everything it has inside of it.This is nice, since we can use this to access the attributes without really accessing them:
We don't want to overwrite any magic (starting and ending with two underscores) attributes, so:
We also don't want to overwrite any builtin functions:
This is where it all comes together.
We use values in
library3
to overwrite the__dict__
oflibrary1
.You can see that
library1
has been overwritten:我找到了一种方法:
I found one way to do that:
您可以使用副本
You can use copy