代码之家  ›  专栏  ›  技术社区  ›  Vishal

我应该把if和elif的通用代码放在哪里?

  •  0
  • Vishal  · 技术社区  · 16 年前

    以下示例:

     if a == 100:
         # Five lines of code
     elif a == 200:
         # Five lines of code
    

    五行代码 是常见的和重复的,我怎样才能避免呢? 我知道把它作为一个函数

    if a == 100 or a == 200:
        # Five lines of code
        if a == 100:
            # Do something
        elif a == 200:
            # Do something
    

    有其他清洁剂吗?

    3 回复  |  直到 16 年前
        1
  •  1
  •   Roger Pate    16 年前

    记住,对于函数,可以使用带有闭包的本地函数。这意味着您可以避免传递重复的参数,并且仍然可以修改局部变量。(只需注意在本地函数中的赋值。另请参见 nonlocal python 3中的关键字。)

    def some_func(a):
      L = []
    
      def append():
        L.append(a)  # for the sake of example
        #...
    
      if a == 100:
        append()
        #...
      elif a == 200:
        append()
        #...
    
        2
  •  4
  •   Eli Bendersky    16 年前

    备选方案(1):在函数中放入5行,然后调用它

    备选方案(2)

    if a in (100, 200):
       # five lines of code
       if a == 100:
          # ...
       else:
          # ...
    

    比你的代码更详细一点

        3
  •  1
  •   ghostdog74    16 年前
    def five_lines(arg):
      ...
    
    if a in [100,200]:
        five_lines(i)