片段会发生变化(遗传算法),所以我更喜欢
使它们与设置分开,设置将保持不变
只是让操作片段变得更加复杂。
无论您在fragment.py 中实现的遗传算法有多复杂,我看不出导入cv2(以及最终更多的模块)会以某种方式影响它。
但是,我同意您声明的第一部分,因为您希望尊重 separation of concerns 的原则并让您的代码更简洁。
我为您的问题看到的解决方案是设置一个配置文件config.py,您可以在其中设置所有导入。但是将config.py 导入其他文件是没有用的,除非您成功地使诸如cv2 之类的模块在其他地方一劳永逸地可用。您可以通过config.py 文件中的dynamically importing them 来实现:
cv2=__import__('cv2')
在您的主程序、fragment.py 文件或任何模块中,您只需运行以下命令即可使用cv2:
import config
config.cv2.imread('pic.png')
import config ↔ 你不再需要运行:import cv2。这是因为此技巧将cv2 呈现为可跨多个模块使用的全局变量。
同样的想法也适用于您需要在 config.py 文件中声明的其他变量,例如 img。
鉴于这些事实,这是我为您的问题提供的解决方案。请注意,我没有使用类和函数:我更喜欢直截了当地解决您的问题,而是让事情变得过于简单明了。
代码组织:
config.py 文件对应于您的wrapper.py:
solution/
├── application.py
├── cfg
│ ├── config.py
│ └── __init__.pyc
├── gallery
│ └── pic.png
└── genalgos
├── fragment.py
└── __init__.py
config.py:
# This will make cv2 global and thus you won't need to import it in ./genalgos/fragment.py
# You can use the same idea for all your other imports
cv2=__import__('cv2')
imgc=cv2.imread('./gallery/pic.png') # imgc is global
fragment.py:
# The only import you can not avoid is this one
import cfg.config
# imgs is global
# By importing cfg.config you do not need to import cv2 here
imgf=cfg.config.cv2.cvtColor(cfg.config.imgc,cfg.config.cv2.COLOR_BGR2GRAY)
application.py:
import cfg.config
import genalgos.fragment
if __name__=="__main__":
"""
Display the image 'imgc' as it is in 'cfg/config' file
"""
cfg.config.cv2.imshow('Pic in BGR',cfg.config.imgc)
cfg.config.cv2.waitKey(0)
cfg.config.cv2.destroyAllWindows()
"""
Display the grascaled image 'imgf' as it is in 'genalgos/fragment' file which
itself is obtained after transforming imgc of 'cfg/config' file.
"""
cfg.config.cv2.imshow('PIC Grayscaled',genalgos.fragment.imgf)
cfg.config.cv2.waitKey(0) # Press any key to exit
cfg.config.cv2.destroyAllWindows() # Unpaint windows and leave