1

Is it possible to define my own mathematical operator?

Like the introduction of the new @ in PEP-465 for matrix multiplication or // for integer division.

Something like

a ! b -> a / (a + b)
Albo
  • 1,584
  • 9
  • 27
  • 2
    Adding those new operators required changes to the language. So in theory you can submit a PEP and get it accepted, implemented, and released in a future version of Python. – khelwood Oct 16 '19 at 10:29
  • Use a function. – rdas Oct 16 '19 at 10:31

1 Answers1

2

You can use one of the predefined operator that has not been implemented for integers.

For example this one : @ (matmul)

You cannot use ! character as it is not in this list.

class MyInt(int):
    def __matmul__(self, other):
        return self / (self + other)

Then you can do :

a = MyInt(1)
b = MyInt(2)
print(a @ b)

Will print (0.33333333)

Corentin Limier
  • 4,946
  • 1
  • 13
  • 24