问题
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