Skip to content

Instantly share code, notes, and snippets.

@devforfu
Last active February 14, 2018 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devforfu/828480bbfd9e12ef27d89dd96914f537 to your computer and use it in GitHub Desktop.
Save devforfu/828480bbfd9e12ef27d89dd96914f537 to your computer and use it in GitHub Desktop.
Simple Example: Step 1
class TemperatureConverter(metaclass=abc.ABCMeta):
"""
Base class of temperature converters which supports dynamic substitution
of implementations.
"""
symbol = 'K'
def __new__(cls, convert_to='celsius'):
if issubclass(cls, TemperatureConverter):
if convert_to == 'celsius':
cls = _CelsiusConverter
elif convert_to == 'fahrenheit':
cls = _FahrenheitConverter
else:
raise ValueError('unexpected converter: %s' % convert_to)
return object.__new__(cls)
def convert(self, value):
self.check_value(value)
return self._convert(value)
def format(self, value):
return ('%.2f' % self.convert(value)) + self.symbol
@staticmethod
def check_value(value):
if value < 0:
raise ValueError('temperature should be provided in Kelvin degrees')
@property
def name(self):
return self.__class__.__name__
def _convert(self, value):
raise NotImplementedError()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment