重用执行标记检查的方法中的代码

时间:2013-06-30 22:45:28

标签: python refactoring

我有一个基于标志调用其他一些方法的方法。

def methodA(self):
    if doc['flag']:
         self.method1()      
         self.method2()

现在,我必须从另一个需要做同样事情的地方调用methodA(),但独立于doc ['flag'](调用self.method1()和self.method2()无论标志是真还是假,都有一个很好的方法吗?

由于

1 个答案:

答案 0 :(得分:2)

你能做到的一种方法是:

def methodA(self):
    if doc['flag']:
        self.anotherMethod()

def anotherMethod(self):
    self.method1()      
    self.method2()

或者:

def methodB(self, flag=False, execute_anyways=False):
    if not flag and not execute_anyways:
        return #Note that while calling, you would be sending True, or False. If flag=None, it would execute. 
    self.method1()      
    self.method2()

def methodA(self):
    self.methodB(flag=doc['flag'])

在另一个例子中,只需致电

self.methodB(execute_anyways=True) #Now, the flag would have the default value of None, and would execute.