None: self.x = num def __div__(self" /> None: self.x = num def __div__(self" /> None: self.x = num def __div__(self"/>

i have an error python OOP. Python magic method __div__()

73 Views Asked by At

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

There are 1 best solutions below

1
Bharel On BEST ANSWER

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