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

如何消除集合标签文本函数中的冗余if语句?

  •  0
  • konichiwa  · 技术社区  · 8 年前

    我有Python函数,用于根据输入参数设置标签。有一个参数叫做 reset 重置所有标签。我怎样才能摆脱多余的 if not reset ? 应该有更聪明的方法。。。

    更新: 我忘了提一个很重要的问题。调用此函数有三种方法:

    1. ft=1,reset=False,t!=没有,a!=无
    2. 英尺!=1,重置=False,i!=无
    3. 重置=1

      定义设置标签文本(fn,ft,t=None,a=None,i=None,reset=False): tt='' 在='' 它=''

      if ft == 1
          if not reset:
              tt = 'bla bla 1 %s' % t
              at = 'bla bla 2 %s' % a
          get_component('template' + ft).get_component(fn + 'Label1').text = tt
          get_component('template' + ft).get_component(fn + 'Label2').text = at
      else:
          if not reset:
              it = 'bla bla 3 %s' % i
          get_component('template' + ft).get_component(fn + 'Label3').text = it
      
    3 回复  |  直到 8 年前
        1
  •  3
  •   Sunitha    8 年前

    把那个 if not reset 排除其他if-else条件块

    def set_labels_text(fn, ft, t=None, a=None, i=None, reset=False):
        tt = ''
        at = ''
        it = ''
    
        if not reset:
            tt = 'bla bla 1 %s' % t
            at = 'bla bla 2 %s' % a
            it = 'bla bla 3 %s' % i
    
        if ft == 1:
            get_component('template' + ft).get_component(fn + 'Label1').text = tt
            get_component('template' + ft).get_component(fn + 'Label2').text = at
        else:
            get_component('template' + ft).get_component(fn + 'Label3').text = it
    
        2
  •  0
  •   user3744881    8 年前

    我想我会用这个办法的!

    def set_labels_text(fn, ft, t=None, a=None, i=None, reset=False):
        at = None
        it = None
        tt = None
        if reset:
            it = 'bla bla 3 %s' % i
        else:
            at = 'bla bla 2 %s' % a
            tt = 'bla bla 1 %s' % t;
    
        if ft == 1
            get_component('template' + ft).get_component(fn + 'Label1').text = tt or ''
            get_component('template' + ft).get_component(fn + 'Label2').text = at or ''
        else:
            get_component('template' + ft).get_component(fn + 'Label3').text = it or ''
    
        3
  •  0
  •   tsabsch    8 年前

    也可以选择使用三值条件运算符 x = y if condition else z ,尽管它需要检查 reset 不止一次:

    def set_labels_text(fn, ft, t=None, a=None, i=None, reset=False):
        if ft == 1:
            tt = 'bla bla 1 %s' % t if not reset else ''
            at = 'bla bla 2 %s' % a if not reset else ''
            get_component('template' + ft).get_component(fn + 'Label1').text = tt
            get_component('template' + ft).get_component(fn + 'Label2').text = at
        else:
            it = 'bla bla 3 %s' % i if not reset else ''
            get_component('template' + ft).get_component(fn + 'Label3').text = it