__div__ not recognized automatically

Peter Otten __peter__ at web.de
Thu Nov 2 09:52:25 EST 2006


Anton81 wrote:

> Hello!
> 
> I wrote a class
> 
> 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?

If you have the

from __future__ import division

statement, you need to override __truediv__(), not __div__()

Peter



More information about the Python-list mailing list