Skip to content

Instantly share code, notes, and snippets.

@maxfischer2781
Created February 23, 2021 10:28
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 maxfischer2781/2e9e23c882b94912b08b63b12aa6a578 to your computer and use it in GitHub Desktop.
Save maxfischer2781/2e9e23c882b94912b08b63b12aa6a578 to your computer and use it in GitHub Desktop.
Example of using `__new__` as a subclass factory
class Number:
def __new__(cls, literal):
for scls in cls.__subclasses__():
try:
return scls(literal)
except (TypeError, ValueError):
pass
raise TypeError("The path to hell is paved with incomplete examples")
# here be numerical operations!
class Integer(Number):
def __new__(cls, literal):
value = int(literal)
self = object.__new__(Integer)
self._value = value
return self
def __repr__(self):
return str(self._value)
class Fraction(Number):
def __new__(cls, literal):
numerator, denominator = map(int, literal.split('/'))
self = object.__new__(Fraction)
self._numerator, self._denominator = numerator, denominator
return self
def __repr__(self):
return f"{self._numerator} / {self._denominator}"
print(Number('12'))
print(Number('12/5'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment