Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.ndarray: converting to a "normal" class

[Python 3]

I like ndarray but I find it annoying to use.

Here's one problem I face. I want to write class Array that will inherit much of the functionality of ndarray, but has only one way to be instantiated: as a zero-filled array of a certain size. I was hoping to write:

class Array(numpy.ndarray):
  def __init__(size):
    # What do here?

I'd like to call super().__init__ with some parameters to create a zero-filled array, but it won't work since ndarray uses a global function numpy.zeros (rather than a constructor) to create a zero-filled array.

Questions:

  1. Why does ndarray use global (module) functions instead of constructors in many cases? It is a big annoyance if I'm trying to reuse them in an object-oriented setting.

  2. What's the best way to define class Array that I need? Should I just manually populate ndarray with zeroes, or is there any way to reuse the zeros function?

like image 430
max Avatar asked Jan 21 '11 10:01

max


People also ask

Is Ndarray a class?

numpy has one main class, ndarray , with a well known set of methods and attributes.

What does Tolist () do in Python?

The tolist() function is used to convert a given array to an ordinary list with the same items, elements, or values.


1 Answers

Why does ndarray use global (module) functions instead of constructors in many cases?

  1. To be compatible/similar to Matlab, where functions like zeros or ones originally came from.
  2. Global factory functions are quick to write and easy to understand. What should the semantics of a constructor be, e.g. how would you express a simple zeros or empty or ones with one single constructor? In fact, such factory functions are quite common, also in other programming languages.

What's the best way to define class Array that I need?

import numpy

class Array(numpy.ndarray):
    def __new__(cls, size):
        result = numpy.ndarray.__new__(Array, size)
        result.fill(0)
        return result
arr = Array(5)

def test(a):
    print type(a), a

test(arr)
test(arr[2:4])
test(arr.view(int))

arr[2:4] = 5.5

test(arr)
test(arr[2:4])
test(arr.view(int))

Note that this is Python 2, but it would require only small modifications to work with Python 3.

like image 83
Philipp Avatar answered Sep 20 '22 10:09

Philipp