overload builtin operator

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Thu Aug 25 16:12:20 CEST 2005

Shaun wrote:
> Hi,
> I'm trying to overload the divide operator in python for basic arithmetic.
> eg. 10/2 ... no classes involved.
> I am attempting to redefine operator.__div__ as follows:
>      # my divide function
>      def safediv(a,b):
>          return ...
>      # reassign buildin __div__
>      import operator
>      operator.__div__ = safediv
> The operator.__dict__ seems to be updated OK but the '/' operator still  
> calls buildin __div__

It won't work that way. You cannot globally modify the behaviour of an operator,
but you can customize how an operator works for your type.


class safeint(int):
    def __div__(self, other):
        return safediv(self, other)



More information about the Python-list mailing list