Skip to main content
 首页 » 编程设计

python之条件执行,无需重复检查条件

2025年02月15日11birdshome

我有一个类,其代码适合以下模板:

class aClass: 
 
    def __init__(self, switch = False): 
        self.switch = switch 
 
    def f(self): 
        done = False 
        while not done: 
 
            # a dozen lines of code 
 
            if self.switch: 
                # a single line of code 
 
            # another dozen lines of code 

因此 if 语句中的单行代码将永远不会 执行,或者将在所有 次迭代中执行。这实际上是在对象初始化时就知道的。

当 self.switch 为 True 时,我希望无需检查 self.switch 即可执行单行代码在每一次迭代中。当 self.switch 为 False 时,我希望忽略一行代码,而不必重复检查 self.switch。

我当然考虑过编写 两个版本 f 并根据 的值在 __init__ 中选择合适的一个switch,但是除了一行之外复制所有这些代码感觉不对。

谁能提出一个优雅的方法来解决这个问题?也许是一种在初始化时生成 f 方法的适当版本的方法?

请您参考如下方法:

这是一个完全有效的问题。如果不是为了性能,那就是为了可读性。

在三个单独的方法和 f() 中提取三个逻辑部分(条件之前、内部和之后),只需编写大循环的两个实现:

def first(self): 
    pass 
 
def second(self): 
    pass 
 
def third(self): 
    pass 
 
def f(self): 
    if self.switch: 
        while ...: 
             self.first() 
             self.third() 
    else: 
         while ...: 
            self.first() 
            self.second() 
            self.third() 

如果你想让它更优雅(虽然这取决于口味),你将我的f()的两个分支表达成两个方法first_loop和second_loop 然后在 __init__ 中分配 self.f = self.first_loop 或 self.f = self.second_loop 取决于 开关:

class SuperUnderperformingAccordingToManyYetReadable(object): 
    def __init__(self, switch): 
        if self.switch: 
            self.f = self._first_loop 
        else: 
            self.f = self._second_loop 
 
    def _first(self): 
        pass 
 
    def _second(self): 
        pass 
 
    def _third(self): 
        pass 
 
    def _first_loop(self): 
        while ...: 
             self.first() 
             self.third() 
 
    def _second_loop(self): 
         while ...: 
            self.first() 
            self.second() 
            self.third() 

您可能需要做一些额外的工作来管理 while 循环的中断。