For example, creating custom number types in following hierarchy
NumberComplexRealIntFloat
with logic in __new__ methods:
class Number:
def __new__(cls, value):
if isinstance(value, complex):
return Complex(value)
elif isinstance(value, (int, float)):
return Real(value)
else:
raise TypeError('Ну ты и мудак!!!')
def __init__(self, value):
self.value = value
class Complex(Number):
pass
class Real(Number):
def __new__(cls, value):
if isinstance(value, int):
return Int(value)
elif isinstance(value, float):
return Float(value)
else:
raise TypeError('Ты больше не можешь вести себя так!!!')
class Int(Real):
pass
class Float(Real):
pass
And then, creating Float instance using Number constructor:
number = Number(6.6)
assert isinstance(number, Float)
This code will raise RuntimeError because of recursion limit. It is just example of desired behaviour. But I also tried to implement this using super and it is seems I misunderstand the world.
@staticmethodon__new__; Python treats it as a static method regardless, not in the least because there is no class or instance to bind to anyway. - Martijn Pieters♦