[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:
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.
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?
numpy has one main class, ndarray , with a well known set of methods and attributes.
The tolist() function is used to convert a given array to an ordinary list with the same items, elements, or values.
Why does ndarray use global (module) functions instead of constructors in many cases?
zeros
or ones
originally came from.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With