__div__ not recognized automatically

Nick Craig-Wood nick at craig-wood.com
Thu Nov 2 08:30:03 EST 2006


Anton81 <usenet1 at anton.e4ward.com> wrote:
>  class NumX:
>    ...
>    def __add__(self,other):
>      ...
>    def __div__(self,other):
>      if not isinstance(other,NumX): other=NumX(other)
>      ...
> 
>  Somewhere else I use
> 
>  a=(b+c)/2
> 
>  where all variables are of NumX Type. When I execute the program it
>  complains that it can't find an operator "/" for "instance" and "integer".
>  However if I use pdb the same command works when started on the prompt. Also
>  the manual execution
> 
>  a=(b+c).__div__(2)
> 
>  works. Any suggestions what goes wrong?

Post some code which actually demonstrates the problem.

Eg, change this code until it does demonstrate the problem

------------------------------------------------------------
class NumX(object):
    def __init__(self, value):
        self.value = long(value)

    def __add__(self,other):
        if not isinstance(other,NumX): other=NumX(other)
        return NumX(self.value + other.value)

    def __div__(self,other):
        if not isinstance(other,NumX): other=NumX(other)
        return NumX(self.value / other.value)

    def __str__(self):
        return "%s(%s)" % (self.__class__.__name__, self.value)

a = NumX(4)
b = NumX(2)

print a,b
print a+b
print (a+b)/2
------------------------------------------------------------

This prints

------------------------------------------------------------
NumX(4) NumX(2)
NumX(6)
NumX(3)
------------------------------------------------------------

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list