operator keyword - Python integer * float = NotImplemented -



operator keyword - Python integer * float = NotImplemented -

so messing around writing vector class when discovered interesting fact.

>>> e = int(3) >>> e.__mul__(3.0) notimplemented

can explain why , subsequently, how prepare vector class?

class vector(tuple): '''a vector representation.''' def __init__(self, iterable): super(vector, self).__init__(iterable) def __add__(self, other): homecoming vector(map(operator.add, self, other)) def __sub__(self, other): homecoming vector(map(operator.sub, self, other)) def __mul__(self, scalar): homecoming vector(map(scalar.__mul__, self)) def __rmul__(self, scalar): homecoming vector(map(scalar.__mul__, self)) def __div__(self, scalar): homecoming vector(map(scalar.__rdiv__, self))

edit: little more clear:

>>> = vector([10, 20]) >>> (10, 20) >>> b = / 2.0 >>> b (5.0, 10.0) >>> 2 * b (notimplemented, notimplemented)

that's because when 3 * 3.0 interpreter calling (3.0).__rmul__(3) after realizing (3).__mul__(3.0) not implemented

float's __mul__ , __rmul__ functions cast integers float should not happen int class.

otherwise 3 * 3.5 9 instead of 10.5

the sec question:

why people insist on map when list comprehensions (and generator expressions) much better?

try that:

def __mul__(self, scalar): homecoming vector(scalar * j j in self)

you should every other function on class.

python operator-keyword

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -