简体   繁体   English

Python:修改导入的类会发生什么?

[英]Python: What happens when I modify imported class?

I have written the following code to modify the behavior of a method of one class 我编写了以下代码来修改一个类的方法的行为

import mymodule
mymodule.MyClass.f = mydecorator(mymodule.MyClass.f)
mymodule.MyClass.f(x) # call the modified function

This works for my purposes, but: what have I modified exactly? 这适用于我的目的,但是:我有什么修改? Is mymodule.MyClass a copy of the original class living inside the current module? mymodule.MyClass是否存在于当前模块中的原始类的副本? Does it in any way affect the original class? 它会以任何方式影响原始课程吗? How does import work exactly? 导入如何正常工作?

When you modify imported module, you modify the cached instance. 修改导入的模块时,可以修改缓存的实例。 Thus your changes will affect all other modules, which import the modified module. 因此,您的更改将影响导入已修改模块的所有其他模块。

https://docs.python.org/3/reference/import.html#the-module-cache https://docs.python.org/3/reference/import.html#the-module-cache

UPDATE: 更新:

You can test it. 你可以测试一下。

change_sys.py: change_sys.py:

import sys

# Let's change a module
sys.t = 3

main.py: main.py:

# the order of imported modules doesn't meter
# they both use cached sys
import sys
import change_sys

print(sys.t)

Output for python ./main.py : python ./main.py输出:

3

It depends. 这取决于。 In normal uses cases everything should be ok. 在正常使用情况下,一切都应该没问题。 But one can imagine special cases where it can lead to weird results: 但是可以想象一下特殊情况会导致奇怪的结果:

a.py: a.py:

import c

x = c.C()

def disp():
    return x.foo()

b.py: b.py:

import c

def change():
    c.C.foo = (lambda self: "bar at " + str(self))

c.py: c.py:

class C:
    def foo(self):
        return "foo at " + str(self)

Now in top level script (or interactive interpretor) I write: 现在在顶级脚本(或交互式解释器)中我写道:

import a
import b
a.disp()
b.change()
a.disp()

Output will be: 输出将是:

'foo at <c.C object at 0x0000013E4A65D080>'
'bar at <c.C object at 0x0000013E4A65D080>'

It may be what you want, but the change has been done in b module and it does affect a module. 这可能是你想要的,但变化已经做过b模块,它确实会影响a模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM