-1

How to define a new arithmetic operation in python

Suppose I want to have operator ? such that A?B will result in A to power of 1/B

So the statement below would be true

A?B == A**(1/B)

for instance in R I can achieve it as following

`?` <- function(A,B) A^(1/B)

4?2
#2
Macosso
  • 1,352
  • 5
  • 22

2 Answers2

3

You can’t.

The set of available operators in Python, with their precedence and associativity, is given by the language spec and can not be changed. Within those bounds, you can define their behaviour for your own classes, by implementing the appropriate “dunder” methods, but you cannot escape ~ being a unary operator.

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15
1

Python has pre-defined operators, including ~. Though you cannot define new operators, you can overload them for your types, so you can define a class with one integer property and overload for the ^ (or any other one in this table):

class MyNumber:
    def __init__(self, x):
       self.x = x

    def __xor__(self, other):
        return self.x ** (1/other.x)

if __name__ == "__main__":
    a = MyNumber(5)
    b = MyNumber(3)
    print(a^b)
Lior v
  • 464
  • 3
  • 12