Is it possible to write vectors in the format i, j, k?

I understand that it would be possible to do something like

i = numpy.array([1,0,0]) j = numpy.array([0,1,0]) k = numpy.array([0,0,1]) a = 2*i + 5*j + 9*k 

but is it possible to use a similar syntax for how complex numbers are executed, and create a class that can define 2i + 5j + 9k , is a member of my class and automatically creates it?

Or would you need to change the python interpreter by changing the way files are handled? I looked at the grammar file, but all I see is NUMBER , and j not mentioned once.

I also looked at parsermodule.c , but could not easily notice something there, which made it obvious how to do this.

Does anyone know how this is possible?

I probably should add that I really do not plan to do this (if by some miracle it turned out that it was not necessary to recompile my own version of python, which would be crazy to do anything other than an academic trip) but just from curiosity about how the language works.

+5
source share
1 answer

You can write a class that inherits from numpy.ndarray (i.e. a subclass) that overrides the repr method (which is responsible for controlling the copying of the object to the console) as follows:

 import numpy class Vector3DDisplay(numpy.ndarray): def __init__(self, vector): if len(vector) == 3: self.vec = numpy.array(vector) else: raise TypeError('Vector must be of length 3.') def __repr__(self): return str(self.vec[0])+'*i + '+str(self.vec[1])+'*j + '+str(self.vec[2])+'*k ' 

You probably noticed an obvious problem: the actual vector is self.vec, not the object itself, so all your numpy operations should be done in the self.vec attribute. The reason is that numpy arrays are written in such a way that they are difficult to subclass (cf this question about subclassing C exentsions ). You usually initialize the array with:

 >>>> import numpy >>>> numpy.ndarray(vector) 

The problem is that np.array is not really a class, but a factory function for the numpy.ndarray class, which is initialized differently and rarely used. You cannot have a method for inheriting objects from a function, so inheritance is not easy.

+1
source

Source: https://habr.com/ru/post/1208746/


All Articles