Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 321
jfboisvieux Avatar asked Nov 23 '16 17:11

jfboisvieux


People also ask

What does unsupported operand type S for /: STR and STR mean?

The Python "TypeError: unsupported operand type(s) for /: 'str' and 'str'" occurs when we try to use the division / operator with two strings. To solve the error, convert the strings to int or float values, e.g. int(my_str_1) / int(my_str_2) . Here is an example of how the error occurs. main.py. Copied!

How do you fix unsupported operand type S for NoneType and int?

Unsupported operand type(s) for +: 'NoneType' and 'int' # The Python "TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'" occurs when we try to use the addition (+) operator with a None value. To solve the error, figure out where the variable got assigned a None value and correct the assignment.

What is operand type S?

There are a number of “unsupported operand type(s)” errors in Python. These errors mean the same thing: you are trying to perform a mathematical operation on a string and a numerical value. Because strings do not support mathematical operations, you'll encounter an error.

What does unsupported operand type S for +: int and list mean?

The Python "TypeError: unsupported operand type(s) for +: 'int' and 'list'" occurs when we try to use the addition (+) operator with a number and a list. To solve the error, figure out where the variable got assigned a list and correct the assignment, or access a specific value in the list.


1 Answers

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

like image 117
turbulencetoo Avatar answered Sep 22 '22 09:09

turbulencetoo