简体   繁体   中英

Arithmetic operators

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

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

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,immaginary):
            self.real=real
            self.immaginary= immaginary 
      def __add__(var):
            c=Complex(self.real + var.real,self.immaginary +v.immaginary)
            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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM