Last active
April 3, 2019 08:28
-
-
Save SebDeclercq/6982cd214ff9b66fa1f42690942eca58 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/usr/bin/env python3 | |
| from typing import Callable | |
| class Converter: | |
| def __init__(self, lang: str = 'en') -> None: | |
| self.lang: str = lang | |
| if self.lang == 'fr': | |
| self.part: str = 'vers' | |
| elif self.lang == 'en': | |
| self.part = 'to' | |
| else: | |
| raise ValueError(f'Unknow lang "{self.lang}"') | |
| def add_conversion(self, orig: str, dest: str, rate: float) -> None: | |
| setattr(self, f'{orig}_{self.part}_{dest}', | |
| self._orig_to_dest(orig, dest, rate)) | |
| setattr(self, f'{dest}_{self.part}_{orig}', | |
| self._orig_to_dest(orig, dest, rate, reverse=True)) | |
| def _orig_to_dest( | |
| self, orig: str, dest: str, rate: float, reverse=False | |
| ) -> Callable: | |
| if not reverse: | |
| def from_to(from_: float) -> float: | |
| return from_ * rate | |
| else: | |
| def from_to(to: float) -> float: | |
| return to / rate | |
| return from_to | |
| def main() -> None: | |
| c: Converter = Converter('en') | |
| c.add_conversion('euro', 'dollar', 1.12) | |
| c.add_conversion('euro', 'pound', .86) | |
| for attr in c.__dict__: | |
| if '_to_' in attr: | |
| print(f'{attr}: {getattr(c, attr)(1):.2f}') | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment