Switch/case en python

Les concepteur de python ont oublié de créer les switch/case. Dommage. Heureusement python est classe.

class switch( object ):
    value = None
    def __new__( class_, value ):
        class_.value = value
        return True

def case( *args ):
    return any( ( arg == switch.value for arg in args ) )

Usage:

while switch( n ):
    if case( 0 ):
        print "You typed zero."
        break
    if case( 1, 4, 9 ):
        print "n is a perfect square."
        break
    if case( 2 ):
        print "n is an even number."
    if case( 2, 3, 5, 7 ):
        print "n is a prime number."
        break
    if case( 6, 8 ):
        print "n is an even number."
        break
    print "Only single-digit numbers are allowed."
    break

source : http://stackoverflow.com/a/6606504

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *


Warning: Declaration of sk2_captcha_plugin::output_plugin_UI() should be compatible with sk2_plugin::output_plugin_UI($output_dls = true) in /home/www-data/bb2k.org/wp-content/plugins/SK2/sk2_plugins/sk2_captcha_plugin.php on line 0

Warning: Declaration of sk2_referrer_check_plugin::output_plugin_UI() should be compatible with sk2_plugin::output_plugin_UI($output_dls = true) in /home/www-data/bb2k.org/wp-content/plugins/SK2/sk2_plugins/sk2_referrer_check_plugin.php on line 0

Warning: Declaration of sk2_rbl_plugin::treat_this($cmt_object) should be compatible with sk2_plugin::treat_this(&$cmt_object) in /home/www-data/bb2k.org/wp-content/plugins/SK2/sk2_plugins/sk2_rbl_plugin.php on line 0

Warning: Declaration of sk2_pjw_simpledigest::output_plugin_UI() should be compatible with sk2_plugin::output_plugin_UI($output_dls = true) in /home/www-data/bb2k.org/wp-content/plugins/SK2/sk2_plugins/sk2_pjw_daily_digest_plugin.php on line 0