0

So I am developing a class for vectorial calculations, and I overwrote the __mul__(self, b) function to do a Scalarproduct. Now whenever I write A * B it calculates as I want it to. So I would like to do the same with an x for the Crossproduct. Sadly there is no default x operator in python, it would probably just annoy you. But is there a way to create your own operator which ONLY works for my own class, but can otherwise be used in a code aswell (as a variable definition I mean)? Or maybe define *** as an operator?

JH_WK
  • 71
  • 1
  • 9
  • 2
    In brief: No, you cannot define your own operators in Python. – DYZ Jan 25 '18 at 06:37
  • As DYZ's pointer question suggests, you may want to check out this hacky approach: http://code.activestate.com/recipes/384122-infix-operators/ – WillMonge Jan 25 '18 at 06:53
  • In recent versions of Python you could override [the `__matmul__` method](https://docs.python.org/3/reference/datamodel.html#object.__matmul__), which is associated with the `@` operator. It's _supposed_ to be for matrix multiplication, but that's not a hard & fast rule. – PM 2Ring Jan 25 '18 at 08:35

1 Answers1

0

Instead of just define an operator, you can write your own interpreter for your own language inside python. Basically, you need to create 4 modules

  • parser

  • environment

  • eval

  • repl

Then you can program with your own language within python.

read Peter Novig's article for a detailed example of a python LISP interpreter

englealuze
  • 1,445
  • 12
  • 19