我刚开始学习编程。我在一个类中创建了以下函数。我注意到我正在重复我的代码。我正在寻找最佳解决方案来消除这种重复。
我在我的类中有以下函数:
def init(self):
if not os.path.exists(self.src_flag):
if os.path.exists(self.src):
removeFolder(self.src)
print 'File {0} does not exist'.format(self.src_flag)
open(self.src_flag, 'a').close()
if not os.path.exists(self.dst_flag):
if os.path.exists(self.dst):
removeFolder(self.dst)
print 'File {0} does not exist'.format(self.dst_flag)
open(self.dst_flag, 'a').close()
然后我通过调用这个函数来实现
Folder.init()
不确定这是否是最佳方案,但我考虑将函数更改为以下内容:
def init(self, flag, path):
if not os.path.exists(flag):
if os.path.exists(path):
removeFolder(path)
print 'File {0} does not exist'.format(flag)
open(flag, 'a').close()
但是我必须运行两次函数才能执行它的src和dst,例如:
Folder.init('C:\src\flag.txt', 'C:\src')
Folder.init('C:\dst\flag.txt', 'C:\dst')
有人能告诉我我的解决方案是否可行,或者是否有更好的方法吗?