简体   繁体   English

算术运算符

[英]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:它创建一个自定义 class 中Infix并实现__or____ror__方法,然后允许以以下方式编写内容:

add = Infix(lambda x,y: x+y)
result = 1 |add| 2

your question as already been answered here: Python: defining my own operators?您的问题已经在这里得到解答: Python:定义我自己的运营商?

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此代码片段是一个常见示例,它创建一个描述复数的 class 并允许您执行Complex_c=Complex_a+Complex_b将复数和存储在Complex_c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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