0

I have "TypeError: unsupported operand type(s) for /: " for this code

class add_object:
    def __init__(self, num) -> None:
        self.x = num
    def __div__(self, other):
        return (self.x / other.x)
n1 = add_object(24)
n2 = add_object(12)
print(n1 / n2)

Error message:

Traceback (most recent call last):
  File "H:\Full Stack Web Development (Python and JavaScript)\Python Django\OOP Project\Basic to advanced oop\OOP-L16.py", line 42, in <module>
    print(n1 / n2)
TypeError: unsupported operand type(s) for /: 'add_object' and 'add_object'
1
  • __div__() has no particular meaning as the name of a method. To implement division of your custom class instances, you want __truediv__() (or __floordiv__() for the // operator). Commented Aug 23, 2022 at 18:14

1 Answer 1

2

Use __truediv__. Python 3 split between __truediv__ and __floordiv__ for true float division and integer (floor-rounded) division respectively.

Sign up to request clarification or add additional context in comments.

1 Comment

__truediv__ is working

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.