Created
February 23, 2021 10:28
-
-
Save maxfischer2781/2e9e23c882b94912b08b63b12aa6a578 to your computer and use it in GitHub Desktop.
Example of using `__new__` as a subclass factory
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
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