Nov-11-2018, 07:02 AM
(This post was last modified: Nov-11-2018, 07:02 AM by MeenakshiAgarwal.)
There is one more elegant way to achieve the switch-case effect in Python, i.e., using the OOPs concept. You can write a switch class with the following pattern.
1- The switch class shall have a switcher function accepting the choice as an argument.
2- This function will call the getattr() method to map options to functions handling individual cases.
3- The getattr() also takes a default function argument which gets returned when there is no other matching function.
4- You also need to define handlers for every case.
A complete example is given here - Python switch-case using classes and dictionary.
1- The switch class shall have a switcher function accepting the choice as an argument.
2- This function will call the getattr() method to map options to functions handling individual cases.
3- The getattr() also takes a default function argument which gets returned when there is no other matching function.
4- You also need to define handlers for every case.
A complete example is given here - Python switch-case using classes and dictionary.