Python: defining my own statements?

I would like to define my own operator. Does python support such a thing?

+53
operators python
May 31 '09 at 16:01
source share
6 answers

No, you cannot create new operators. However, if you simply evaluate expressions, you can process the string yourself and calculate the results of the new operators.

+28
May 31 '09 at 16:06
source share

While technically you cannot define new operators in Python, this smart hack works around this limitation. This allows you to define infix statements like this:

# simple multiplication x=Infix(lambda x,y: x*y) print 2 |x| 4 # => 8 # class checking isa=Infix(lambda x,y: x.__class__==y.__class__) print [1,2,3] |isa| [] print [1,2,3] <<isa>> [] # => True 
+148
May 31 '09 at 18:18
source share

No, Python comes with a predefined, but redefined, set of statements .

+37
May 31 '09 at 16:03
source share

If you intend to apply the operation to a specific class of objects, you can simply override the operator that matches your function, the closest ... for example, overriding __eq__() override the == operator to return everything you want. This works for almost all operators.

+8
May 31 '09 at 16:27
source share

Sage provides this functionality, mainly using the β€œsmart hack” described by @Ayman Hourieh, but built into the module as a decorator to provide a cleaner look and additional functionality - you can choose an operator to overload and, therefore, order evaluation.

 from sage.misc.decorators import infix_operator @infix_operator('multiply') def dot(a,b): return a.dot_product(b) u=vector([1,2,3]) v=vector([5,4,3]) print(u *dot* v) # => 22 @infix_operator('or') def plus(x,y): return x*y print(2 |plus| 4) # => 6 

For more information, see the Sage documentation and this ticket to track improvements .

+7
Dec 18 '13 at 19:47
source share

Python 3.5 introduces the @ character for an optional operator.

PEP465 introduced this new operator for matrix multiplication to simplify the notation of many numeric codes. The operator will not be implemented for all types, but only for objects like arrays.

You can support the operator for your classes / objects by implementing __matmul__() .

PEP leaves room for another use of the operator for non-array objects.

Of course, you can implement with @ any operation other than matrix multiplication for objects like arrays, but this will affect the user's work, because everyone will expect your data type to behave differently.

+7
Jan 09 '15 at 10:32
source share



All Articles