你
Complex,
Float而
Int类也 不能 有
__new__方法,让他们继承这些从
Number; 这就是导致您无限递归的原因。
您可以针对
__class__闭包进行测试,以查看是否具有子类:
class Number: def __new__(cls, value): if cls is not __class__: # Subclass, create an instance (invokes object.__new__) return super().__new__(cls) 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
并在
Real:
class Real(Number): def __new__(cls, value): if cls is not __class__: # Subclass, create an instance return super().__new__(cls, value) if isinstance(value, int): return Int(value) elif isinstance(value, float): return Float(value) else: raise TypeError('Ты больше не можешь вести себя так!!!')
演示:
>>> class Number:... def __new__(cls, value):... if cls is not __class__:... # Subclass, create an instance... return super().__new__(cls)... 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 Real(Number):... def __new__(cls, value):... if cls is not __class__:... # Subclass, create an instance... return super().__new__(cls, value)... if isinstance(value, int):... return Int(value)... elif isinstance(value, float):... return Float(value)... else:... raise TypeError('Ты больше не можешь вести себя так!!!')... >>> class Complex(Number):... pass... >>> class Int(Real):... pass... >>> class Float(Real):... pass... >>> number = Number(6.6)>>> isinstance(number, Float)True
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)