Last active
February 28, 2022 14:32
-
-
Save toanalien/cffce7fbedf474b1f5702a352fd3a426 to your computer and use it in GitHub Desktop.
switch/case python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def numbers_to_strings(argument): | |
switcher = { | |
0: "zero", | |
1: "one", | |
2: "two", | |
} | |
return switcher.get(argument, "nothing") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def zero(): | |
return "zero" | |
def one(): | |
return "one" | |
def numbers_to_functions_to_strings(argument): | |
switcher = { | |
0: zero, | |
1: one, | |
2: lambda: "two", | |
} | |
# Get the function from switcher dictionary | |
func = switcher.get(argument, lambda: "nothing") | |
# Execute the function | |
return func() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Switcher(object): | |
def numbers_to_methods_to_strings(self, argument): | |
"""Dispatch method""" | |
# prefix the method_name with 'number_' because method names | |
# cannot begin with an integer. | |
method_name = 'number_' + str(argument) | |
# Get the method from 'self'. Default to a lambda. | |
method = getattr(self, method_name, lambda: "nothing") | |
# Call the method as we return it | |
return method() | |
def number_0(self): | |
return "zero" | |
def number_1(self): | |
return "one" | |
def number_2(self): | |
return "two" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function(argument){ | |
switch(argument) { | |
case 0: | |
return "zero"; | |
case 1: | |
return "one"; | |
case 2: | |
return "two"; | |
default: | |
return "nothing"; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment