![]() This interface will only work for some numpy functions, but not all. Unfortunately, that is not entirely true. Since np.mean has been registered in HANDELED_FUNCTIONS, we use it to call instead our version of np.mean : here HANDLED_FUNCTIONS(*args, **kwargs) is the equivalent to np_mean_for_physical(*args, **kwargs).Īnd that is how you can make numpy’s function work with your custom class. Well, since numpy fails to compute the mean, as we saw above, it checks if bmi has a _array_function_ method, and calls it with the function that was used on bmi, ie np.mean : bmi._array_function_(np.mean, *args, **kwargs). So what happens then when we call np.mean(bmi) ? finally, we use the implements decorator on that function.then create a new Physical instance using the mean as value, and the input’s unit as unit.compute the numerical mean using the value of x, x._value, which is a plain array.It has roughly the same signature as np.mean, and does the following: Fourth, there is our implementation of numpy’s mean to handle physical instances, when np.mean(x) is called with x being a Physical instance.Our implements decorator simply creates the correspondance in our HANDLED_FUNCTION dictionnary between a numpy function, and a func, that is meant to be our version of the numpy function. Third, we create a decorator constructor : that is a function that returns a decorator (ie, another function that take a function as argument).We’ll come back to the content of this method in a minute. Second, we add a method called _array_function_ to our class that takes, among others, a parameter called func.First, we create an empty dictionnary above our class definition called HANDLED_FUNCTION =.Let’s review what we added to the code to achieve this. Hurray again, np.mean(bmi) returns the “mean” of our physical array, which is indeed a physical quantity, with unit “kilogram/meter^2”. Using the _array_function_ interface to implement np.mean support
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |