Last active
December 15, 2015 23:59
-
-
Save majorz/5344793 to your computer and use it in GitHub Desktop.
MRO iteration solution
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
from abc import ABCMeta | |
class Renderer(metaclass=ABCMeta): | |
def __init__(self, entity): | |
self._entity = entity | |
self._render_entity = self._locate_renderer() | |
def _locate_renderer(self): | |
for cls in self.__class__.mro(): | |
if not hasattr(cls, '_type'): | |
raise TypeError('Cannot render {!r}'.format(self._entity)) | |
if isinstance(self._entity, cls._type): | |
return cls._render | |
def __call__(self): | |
return self._render_entity(self) | |
class IntRenderer(Renderer): | |
_type = int | |
def _render(self): | |
return 'INTEGER {}'.format(self._entity) | |
class FloatRenderer(Renderer): | |
_type = float | |
def _render(self): | |
return 'FLOAT {}'.format(self._entity) | |
class CompositeRenderer( | |
IntRenderer, | |
FloatRenderer, | |
): | |
pass | |
if __name__ == '__main__': | |
numbers = [10, 4.1, 91.1, 1000] | |
for number in numbers: | |
renderer = CompositeRenderer(number) | |
print(renderer()) | |
''' | |
OUTPUT: | |
INTEGER 10 | |
FLOAT 4.1 | |
FLOAT 91.1 | |
INTEGER 1000 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment