简体   繁体   中英

How to eliminate redundant if statement in set label text function?

I have Python functions that is used to set labels based on input parameters. There is a parameter called reset which resets all labels. How can I get rid of redundant if not reset ? There should be a smarter approach...

UPDATE: I forgot to mention a pretty significant point. There are 3 ways of calling this function:

  1. ft = 1 and reset = False, t != None, a != None
  2. ft != 1 and reset = False, i != None
  3. reset = 1

    def set_labels_text(fn, ft, t=None, a=None, i=None, reset=False): tt = '' at = '' it = ''

     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 

How about moving the if not reset block out of the other if else condition blocks

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

I think I would go for this solution!

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 ''

There is also the option of using the ternary condition operator x = y if condition else z , although it requires checking the state of reset more than once:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM