user3286067
user3286067

Reputation: 31

Operator overloading python

> class divnum:
>     def __init__(self,num):
>         self.nums=num
>     def __div__(self,other):
>         return self.nums/other.nums 
> a=divnum(5)  
> b=divnum(1)
> answer= (a/b)

This error "builtins.TypeError: unsupported operand type(s) for /: 'divnum' and 'divnum'". what i wrong?

Upvotes: 2

Views: 214

Answers (1)

M4rtini
M4rtini

Reputation: 13539

Assuming this is Python 3.x

To implement the division operator for a class, there are two methods: __floordiv__ and __truediv__. integer and float division respectively.

If you only implement one of them, you get the TypeError you experienced when trying to do the other.

In python 3.x the default is float division, unless you use //. So you should implement __truediv__ in your class unless you only want integer division to be possible.

I don't have python 3.x myself, so i can't test this. But i think this should be right.

class divnum:
    def __init__(self,num):
         self.nums=num
    def __truediv__(self,other):
         return self.nums/other.nums

    def __floordiv__(self, other):
        return self.nums//other.nums 

Upvotes: 2

Related Questions