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'
Anik Saha
  • 97
  • 6
  • `__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). – jasonharper Aug 23 '22 at 18:14

1 Answers1

1

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

Bharel
  • 23,672
  • 5
  • 40
  • 80