Сначала вы проверяете тип в __mul__
для MyFloatExt
, должно выглядеть
isinstance(other,(int,long,float))
или даже лучше
isinstance(other,Number) #from numbers import Number
Также вы хотели бы изменить определение __mul__
в MyFloat
к этому:
class MyFloat(object):
#...
def __mul__(self, other):
return type(self)(self.a * other.a)
#...
, чтобы он мог создавать экземпляры вашего фактического типа
И вы можете предпочесть вызов super
вместо вызова MyFloat.__mul__
по причинам эволюции вашегоиерархии типов.
полный источник:
from numbers import Number
class MyFloat(object):
def __init__(self, a):
self.a = a
def __mul__(self, other):
return type(self)(self.a * other.a)
def __repr__(self):
return str(self.a)
class MyFloatExt(MyFloat):
def __init__(self, a):
super(MyFloatExt,self).__init__(a)
def __add__(self, other):
return type(self)(self.a + other.a)
def __mul__(self, other):
if isinstance(other,Number):
return type(self)(self.a * other)
else:
return super(MyFloatExt,self).__mul__(other)
a = MyFloatExt(0.5)
b = MyFloatExt(1.5)
c = a + b
print c
d = a * b
print d
e = d * c
print e
print isinstance(e, MyFloat)
f = e * 0.5
print f
print map(type,[a,b,c,d,e,f]) == [MyFloatExt]*6