在下面的Python程序结构中,有两个具有函数的模块。
问题描述:
问题:,改进这个设计的好方法是什么?
例如,将函数从助手模块2传递到模块1中的函数作为参数?如果这样做,模块2中的函数仍然相互依赖(例如,funct4()使用funcr1()、funct2()、funct3()等)
我从我的范式开始:我在想:“啊,我将有一个主要发生的主要模块。然后我将有一个辅助模块,用于做一些准备工作和清理工作,并从模块1调用它们。”(好吧,现在我有这么多麻烦了。)我想知道一个好的设计是否能减少功能之间的相互依赖?每个函数只做一件事而不调用其他函数??我应该上课吗?多么?是关于何时使用类与模块的问题吗?功能设计与面向对象设计?
您将如何重新设计这一点,使尽可能少的耦合和文件只读一次(或尽可能少读)?
谢谢你的建议。
模块1 (主模块,在这里执行程序) 从module2进口* f1()
发布于 2015-03-23 22:58:14
假设文件没有被写入,我已经创建了一个非常简单的概要,说明了一种减少文件打开和关闭次数的方法。以及调用其他函数的次数。在初始化Helpers()时,它们应该只运行一次。尽管如此,这并没有真正减少耦合的数量,因为帮助者的本质。
module2:
class Helpers(object):
def __init__(self, fp=None):
self.contents = self.func1(self.fp)
self.func2_results = self.func2()
self.func3_results = self.func3()
self.func4_results = self.func4()
self.results = {'name2':self.func2_results,
'name3':self.func3_results,
'name4':self.func4_results
}
def func1(self):
# read file
with open(...) as f:
contents = f.read()
return contents
def func2(self):
# doStuff(self.contents)
return something
def func3(self):
# doStuff(self.contents)
return something
def func4(self):
# func2 and func3 were already run once in init
# so lets use the results from them
# self.func2_results
# self.func2_results
# self.func3_results
return something module1:
from module2 import Helpers
class Main(object):
def __init__(self, fp=None):
self.helper = Helpers(self.fp)
self.contents = self.helper.contents
self.name2 = self.helper.results['name2']
self.name3 = self.helper.results['name3']
self.name4 = self.helper.results['name4']
def f1(self):
# doStuff(self.contents)
# doStuff(self.name2)
return thing1
def f2(self):
# doStuff(self.contents)
# doStuff(self.name2)
return thing2
def f3(self):
# doStuff(self.helper.contents)
return thing3
def f4(self):
# doStuff(self.name2)
# doStuff(self.name3)
# doStuff(self.name4)
return thing4
def f5(self):
# doStuff(self.contents)
# doStuff(self.name2)
# doStuff(self.name4)
return thing5
def f6(self):
# doStuff(self.contents)
# doStuff(self.name2)
# doStuff(self.name4)
return thing6然后它就可以像:
from module1 import Main
here = Main(fp="/some/file.xml")
here2 = Main(fp="/some/file2.xml")
print(here.name2)
print(here.name3)
print(here.name4)
# each method will have only run once
f1 = here.f1()
f2 = here.f2()
f3 = here.f3()
f4 = here.f4()
f5 = here.f5()
f6 = here.f6()
# these will run the helpers again from within `Helpers()`
# say for example if the file contents have been updated
h1 = here.helper.func1()
h2 = here.helper.func2()
h3 = here.helper.func3()
h4 = here.helper.func4()https://stackoverflow.com/questions/29221221
复制相似问题