Can I create a class that will be created using non-trivial syntax?

Consider, for example, quaternion math ( https://en.wikipedia.org/wiki/Quaternion ).

Obviously, I can build a class that defines a new quaternion

a = quaternion(1, 2, 3, 4)
print(a)
# 1 + 2i + 3j + 4k

However, one cannot fail to notice that the native data type complexcan be defined much better using

a = 1 + 2j
type(a)
# complex or <class 'complex'> depending if ipython or python

The syntax 1 + 2jis somehow captured to create a built-in class of complex (1,2) objects.

So can I do the same? Is there a way to capture simple direct syntax, for example a = 1 + 2i + 3j + 4k, and translate it into mine a = quartenion(1, 2, 3, 4)in a way similar to the built-in ones complex?

+4
source share
2 answers

: , .

: , , .

python. python . python. python, . . , python.

(, ++) , , , from myquaternionlibrary import q, q("1 + 2j + 3k + 4h"), , . q .

- Quaternions python. python-ideas ( , , ; , ), , . PEP , CPython python.

( - , python , , .)

+2

, , .

# quaternion.py
...
i = quaternion(0, 1, 0, 0)
j = quaternion(0, 0, 1, 0)
k = quaternion(0, 0, 0, 1)

# main.py
from quaternion import i,j,k
a = 1 + 2*i + 3*j + 4*k

, , .

+4

All Articles