[Tutor] __mul__ for different variable types?

Warren warren at wantonhubris.com
Sun Oct 4 23:44:31 CEST 2009


Awesome, Rich, thanks!

- Warren
(warren at wantonhubris.com)




On Oct 4, 2009, at 5:31 PM, Rich Lovely wrote:

> 2009/10/4 Warren <warren at wantonhubris.com>:
>>
>> I'm a little confused on this one.
>>
>> I have a Vector class that I want to be able to multiply by either  
>> another
>> vector or by a single float value.  How would I implement this in my
>> override of __mul__ within that class?
>>
>> Do you check the variable type with a stack of "if isinstance"  
>> statements or
>> something?  What is the preferred Python way of doing this?
>>
>> - Warren
>> (warren at wantonhubris.com)
>>
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> I think isinstance is probably the most pythonic way of doing this,
> and don't forget to add __rmul__ as well, for floats:
>
> try:
>    from numbers import Real
> except NameError:
>    Real = (int, long, float)
>
> class Vector(object):
>    #__init__ and other methods ommitted.
>    def __mul__(self, other):
>        """self * other"""
>        if isinstance(other, Vector):
>            # code for Vector * Vector
>        elif isinstance(other, Number):
>            # code for Vector * number
>        else:
>            return NotImplemented
>    def __rmul__(self, other):
>        """other * self"""
>        return self.__mul__(other)
>
> Note that I've got no type checking in __rmul__, because if only
> Vector * Vector has a different value if the terms are swapped, and
> other * self will use other.__mul__ if other is a Vector.
>
> Also note the import at the top:  numbers.Real is an Abstract Base
> Class use for all real number types, introduced in Python 2.6, so
> simplifies testing types.  See
> http://docs.python.org/library/numbers.html for info.  If it's not
> there, the code demos another feature of isinstance most people don't
> notice: the type argument can be a sequence of types,  so I set Real
> to a tuple of all the builtin real number types (that I can remember
> off the top of my head) if the import fails.
>
> If you want multiplication to be defined for complex numbers, change
> all occurances of Real to Number, and add complex to the tuple.
>
> -- 
> Rich "Roadie Rich" Lovely
>
> There are 10 types of people in the world: those who know binary,
> those who do not, and those who are off by one.



More information about the Tutor mailing list