2
> 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?

4
  • What version of python? This works in 2.7 Commented Feb 8, 2014 at 1:39
  • 1
    Probably python version 3.x Since it would do float division by default, which is implemented by __truediv__ Commented Feb 8, 2014 at 1:40
  • 1
    Why was this downvoted? It's a perfectly reasonable beginner question, and one on which it's easy to be misled by lots of examples on the web which are Py 2-centric. Commented Feb 8, 2014 at 2:22
  • @user3286067 if M4rtini answer helped you, please consider accepting it as the answer by clicking on the "v" at the left of it. This way, future readers will know it is the correct solution. Commented Feb 8, 2014 at 2:36

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

2 Comments

__truediv__ and __floordiv__, not __truediv__ and __div__.
Thank you for answer. I can run truediv. Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.