2

As you know there are arithmetic operators like + or -. Is there a way to create my own operator which can execute a specific task between two variables?

For example:

a, b = 2, 5
a '+' b == 7

What I would like to do:

a 'my own operator' b == some_specific_value
a_guest
36.7k15 gold badges75 silver badges137 bronze badges
asked Nov 30, 2021 at 17:07

2 Answers 2

1

There is a recipe for how to mimic custom infix operators. It creates a custom class Infix and implements the __or__ and __ror__ methods which then allows to write things in the following way:

add = Infix(lambda x,y: x+y)
result = 1 |add| 2
answered Nov 30, 2021 at 17:19
Sign up to request clarification or add additional context in comments.

Comments

1

your question as already been answered here: Python: defining my own operators?

A little addition to what was said on that tread would be that if you define custom objects then you can define the effect of an operator between two objects of the same type:


class Complex:
 def __init__(self,real,imaginary):
 self.real=real
 self.imaginary= imaginary 
 def __add__(var):
 c=Complex(self.real + var.real,self.imaginary +v.imaginary)
 return c

This code snippet is a common example that creates a class that describes complex numbers and allowes you to do Complex_c=Complex_a+Complex_b store the complex sum in Complex_c

answered Nov 30, 2021 at 17:20

2 Comments

Although complex numbers are already there: print((1+1j) + (1-1j)) prints (2+0j). Also "imaginary" has only one 'm'.
Sorry for the „m" abundance!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.