Clone a module and make changes to the copy

我是研究僧i 提交于 2019-12-07 03:07:43

问题


Is it possible to copy a module, and then make changes to the copy? To phrase another way, can I inherit from a module, and then override or modify parts of it?


回答1:


To phrase another way, can I inherit from a module, and then override or modify parts of it?

Yes.

import module

You can use stuff from module or override stuff in your script.

You can also do this to create a "derived" module.

Call this "module_2".

from module import *

Which imports everything. You can then use stuff from module or override stuff in this new module, "module_2".

Other scripts can then do

import module_2

And get all the stuff from module modified by the overrides in module_2.




回答2:


The namespace of a Python module is writable. Consider:

# contrived.py
CONST = 100
def foo():
    return CONST

You can modify the value of CONST after it's been imported:

import contrived
contrived.CONST = 200
contrived.foo() # 200

However, only a single instance of a module can be imported so there is not anyway to create a clone and continue to use the original module. If you don't need access to the original module, then it's fairly straight-forward to create a wrapper module and override whatever you want to change.

One thing to look out for is that code like this will not work as you expect:

# clone.py
from contrived import *
CONST = 200

This will actually assign CONST in clone's namespace, functions imported from contrived will continue to reference the CONST in contrive's namespace:

import clone
clone.foo() # 100

In this case you could do something like this:

# clone.py
import contrived
contrived.CONST = 200
from contrived import *


来源:https://stackoverflow.com/questions/7483022/clone-a-module-and-make-changes-to-the-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!