So I was messing around writing a vector class when I discovered this interesting fact.
>>> e = int(3)
>>> e.__mul__(3.0)
NotImplemented
Can anyone explain why this is and subsequently, how to fix my vector class?
class Vector(tuple):
'''A vector representation.'''
def __init__(self, iterable):
super(Vector, self).__init__(iterable)
def __add__(self, other):
return Vector(map(operator.add, self, other))
def __sub__(self, other):
return Vector(map(operator.sub, self, other))
def __mul__(self, scalar):
return Vector(map(scalar.__mul__, self))
def __rmul__(self, scalar):
return Vector(map(scalar.__mul__, self))
def __div__(self, scalar):
return Vector(map(scalar.__rdiv__, self))
EDIT: To be a little more clear:
>>> a = Vector([10, 20])
>>> a
(10, 20)
>>> b = a / 2.0
>>> b
(5.0, 10.0)
>>> 2 * b
(NotImplemented, NotImplemented)
That’s because when you do
3 * 3.0the interpreter is calling(3.0).__rmul__(3)after realizing that(3).__mul__(3.0)is not implementedFloat’s
__mul__and__rmul__functions do cast integers to float but that should not happen with the int class.Otherwise
3 * 3.5would be9instead of10.5The second question:
Why do people insist on
mapwhen list comprehensions (and generator expressions) are much better?try that:
You should do that to every other function on the class.