jfboisvieux
jfboisvieux

Reputation: 157

TypeError: unsupported operand type(s) for /:

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

class Foo(object):
    def __add__(self, other):
        return print("add")
    def __div__(self, other):
        return print("div")


Foo() + Foo()
add

** BUT for / **

Foo() / Foo()
Traceback (most recent call last):

  File "<ipython-input-104-8efbe0dde481>", line 1, in <module>
    Foo() / Foo()

TypeError: unsupported operand type(s) for /: 'Foo' and 'Foo'

Upvotes: 7

Views: 10641

Answers (2)

neverwalkaloner
neverwalkaloner

Reputation: 47374

In python3 you can use truediv:

class Foo(object):
    def __add__(self, other):
        return print("add")
    def __truediv__(self, other):
        return print("div")

Upvotes: 0

turbulencetoo
turbulencetoo

Reputation: 3701

Python3 uses special division names: __truediv__ and __floordiv__ for the / and // operators, respectively.

In Python3, the / is a true division in that 5/2 will return the floating point number 2.5. Similarly 5//2 is a floor division or integer division because it will always return an int, in this case 2.

In Python2 the / operator worked the same way that the // operator works in Python3. Because of the way that the operators changed between versions, the __div__ name was removed to to avoid ambiguity.

Reference: http://www.diveintopython3.net/special-method-names.html#acts-like-number

Upvotes: 20

Related Questions