Created
August 13, 2020 19:09
-
-
Save sh1ma/54b66ca9b2e5e378280bef4a8235ab84 to your computer and use it in GitHub Desktop.
pythonでcase
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
import enum | |
class Color(enum.Enum): | |
BLACK = enum.auto() | |
WHITE = enum.auto() | |
color_text = "black" | |
class Switch: | |
def __init__(self, *cases, default=None): | |
self.patterns_dict = {case.pattern: case.ret for case in cases} | |
if default is not None: | |
self.default = default | |
else: | |
self.default = Exception("Default") | |
def __call__(self, arg): | |
if arg not in self.patterns_dict: | |
if isinstance(self.default, Exception): | |
raise self.default() | |
else: | |
return self.default() | |
return self.patterns_dict[arg] | |
class Case: | |
def __init__(self, pattern, ret): | |
self.pattern = pattern | |
self.ret = ret | |
@classmethod | |
def case(cls, pattern, ret): | |
return cls(pattern, ret) | |
def get_color(color_text: str): | |
color = Switch( | |
Case.case("black", Color.BLACK), | |
Case.case("white", Color.WHITE), | |
default=lambda: "Unknown", | |
)(color_text) | |
return color | |
print(get_color("aaa")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment