python - 重用执行标志检查的方法中的代码

标签 python refactoring

我有一个方法,它根据标志调用其他一些方法..

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

现在,我必须从另一个地方调用 methodA() ,它需要做基本上相同的事情,但独立于 doc['flag'] (调用 self.method1() 和 self.method2()无论标志是真还是假)有没有一个好的方法来做到这一点?

谢谢

最佳答案

一种方法是:

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. 

关于python - 重用执行标志检查的方法中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17395521/

相关文章:

Python 请求 API 使用代理进行 https 请求获取 407 需要代理身份验证

可以访问包括单词定义在内的英语词典的 Python 模块

python - 关于使用 Ropevim 的任何指示?它是一个可用的库吗?

java - Java中不同类型变量转换的工具

python - DataFrame 列的所有可能组合 - pandas/python

python - 当默认提供的不是元组时,为什么 python 中的链式字典 .get() 返回元组?

python - 尝试创建一个Python网络爬虫

java - Web 应用程序的硬件支持

Swift:在另一个 switch 语句中重构 switch 语句

c# - 您将如何重构它以使其更好?