-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
1
  • 1
    ~ sign is already taken in python: it's bitwise NOT operator, you shouldn't override it Commented Apr 29, 2023 at 11:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.