473,597 Members | 2,749 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Subclassing numarray's arrays

I'd like to subclass numarray's array. I'd like to add some methods
and override others like __init__. I don't know how to do this and
haven't found help searching the manual or the web, can someone help?

For example imagine I just want to do something as simple as making a
subclass "NewClass" with the __init__ method overridden so that the
behaviour would be:
a = NewClass(2)
print a

[[2 2]
[2 2]]

How could that be done?

Thanks in advance, miz.
Jul 18 '05 #1
3 1548


Mizrandir wrote:
I'd like to subclass numarray's array. I'd like to add some methods
and override others like __init__. I don't know how to do this and
haven't found help searching the manual or the web, can someone help?

For example imagine I just want to do something as simple as making a
subclass "NewClass" with the __init__ method overridden so that the
behaviour would be:

a = NewClass(2)
print a


[[2 2]
[2 2]]

How could that be done?

Thanks in advance, miz.

Miz,

Numarray wasn't designed with subclassing in mind, but there are
workarounds for most problems.

You might try something like:
import numarray.numarr aycore as _num
class NewClass(_num.N umArray):
def __init__(self, n, a):
''' n provides the length of each dimension,
a is the constant value to be plugged.
'''
arr= _num.array(sequ ence= n * n * [a], shape= (n, n))
self.__setstate __(arr.__getsta te__())

def __repr__(self):
" Return printable representation of instance."
className= self.__class__. __name__
className= className.zfill (5).replace('0' , ' ')
arr= self.copy()
arr.__class__= _num.NumArray
rep= className + _num.NumArray._ _repr__(arr)[5:]
return rep

def __str__(self):
" Return a pretty printed string of the instance."
stri= self.copy()
stri.__class__= _num.NumArray
return _num.NumArray._ _str__(stri)
if __name__ == '__main__':
a= NewClass(2, 2)
print a
b= NewClass(3, 4)
print `b`

I hope that this helps.

Colin W.

Jul 18 '05 #2
First of all, thanks for helping.
Numarray wasn't designed with subclassing in mind, but there are
workarounds for most problems.
On numarray's website there is a paper by the Numarray authors saying:
"... The new approach allows arrays to be subclassed as well as ...",
so I thought it should be something easy to do.

Anyway, I hadn't read anything about numarraycore, is it explained
anywhere. For example, I don't understand what the statement
"self.__setstat e__(arr.__getst ate__())" does.

You might try something like:
import numarray.numarr aycore as _num
class NewClass(_num.N umArray):
def __init__(self, n, a):
''' n provides the length of each dimension,
a is the constant value to be plugged.
'''
arr= _num.array(sequ ence= n * n * [a], shape= (n, n))
self.__setstate __(arr.__getsta te__())

def __repr__(self):
" Return printable representation of instance."
className= self.__class__. __name__
className= className.zfill (5).replace('0' , ' ')
arr= self.copy()
arr.__class__= _num.NumArray
rep= className + _num.NumArray._ _repr__(arr)[5:]
return rep

def __str__(self):
" Return a pretty printed string of the instance."
stri= self.copy()
stri.__class__= _num.NumArray
return _num.NumArray._ _str__(stri)
if __name__ == '__main__':
a= NewClass(2, 2)
print a
b= NewClass(3, 4)
print `b`


miz.
Jul 18 '05 #3


Mizrandir wrote:
First of all, thanks for helping.

Numarray wasn't designed with subclassing in mind, but there are
workarounds for most problems.

On numarray's website there is a paper by the Numarray authors saying:
"... The new approach allows arrays to be subclassed as well as ...",
so I thought it should be something easy to do.

I don't remember that, but it is not as dificult as it looks. Just try
out the code below, nothing could be simpler than the __init__ method
below.

The __str__ and __repr__ are just tools which can be used with any subclass.
Anyway, I hadn't read anything about numarraycore, is it explained
anywhere. For example, I don't understand what the statement
"self.__setstat e__(arr.__getst ate__())" does.
NumArray creates a number of attributes to provide information about the
shape of an array, the data type of its elements and to point to the
memory buffer containing the binary data etc. The expression above just
transfers the values from arr (which is an instance of NumArray) to
self (which is an instance of NewClass).
You might try something like:
import numarray.numarr aycore as _num
class NewClass(_num.N umArray):
def __init__(self, n, a):
''' n provides the length of each dimension,
a is the constant value to be plugged.
'''
arr= _num.array(sequ ence= n * n * [a], shape= (n, n))
self.__setstate __(arr.__getsta te__())

def __repr__(self):
" Return printable representation of instance."
className= self.__class__. __name__
className= className.zfill (5).replace('0' , ' ')
arr= self.copy()
arr.__class__= _num.NumArray
rep= className + _num.NumArray._ _repr__(arr)[5:]
return rep

def __str__(self):
" Return a pretty printed string of the instance."
stri= self.copy()
stri.__class__= _num.NumArray
return _num.NumArray._ _str__(stri)
if __name__ == '__main__':
a= NewClass(2, 2)
print a
b= NewClass(3, 4)
print `b`

miz.

Please let me know if I can provide any further information. numarray
is a good tool, but there is a small hurdle if one wishes to subclass.

Colin W.

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1907
by: Tim Rowe | last post by:
Does numarray-0.5.win32-py2.2.exe work with Python 2.3? If not, is there a version that will? Tia, Tim
8
1791
by: Russell E. Owen | last post by:
I'm writing a C extension for numarray and am puzzled about the idiom for error handling. The documentation seems to say one should always decref an array after calling NA_InputArray, etc., to convert numarray args to C arrays. However, the example and also the numarray code suggests that it's OK to return early via (for example) PyErr_Format without doing the DECREF. For example, I have appended a very abbreviated version of the...
11
1980
by: grv | last post by:
So it is supposed to be very fast to have an array of say 5 million integers stored in a binary file and do a = numarray.fromfile('filename', (2, 2, 2)) numarray.add(a, 9, a) but how is that faster than reading the entire file into memory and then having a for loop in C: (loop over range) { *p++ += 9 }
4
3134
by: Ben Champion | last post by:
I have installed python 2.3.3 on my windows machine have have ran several programs succesfully. I have also installed numarray 1.1 for my version of python and am now trying to create arrays using the array command, eg >>>Import Numeric >>> a = array() Traceback (most recent call last): File "<pyshell#1>", line 1, in -toplevel-
1
3205
by: Chris P. | last post by:
Hi. I have a very simple task to perform and I'm having a hard time doing it. Given an array called 'x' (created using the numarray library), is there a single command that rounds each of its elements to the nearest integer? I've already tried something like >>> x_rounded = x.astype(numarray.Int) but that only truncates each element (i.e. '5.9' becomes '5'). I've read over all the relevant numarray documentation, and it
5
1491
by: George Sakkis | last post by:
What's the fastest and most elegant equivalent of zip() in Numeric/Numarray between two equally sized 1D arrays ? That is, how to combine two (N,)-shaped arrays to one (N,2) (or (2,N)) shaped ? I expect the fastest and the most elegant idiom to be identical, as it is usually the case in this excellent library, but if not, both would be useful to know. Thanks, George
6
1478
by: Matt Feinstein | last post by:
Is there an optimal way to apply a function to the elements of a two-d array? What I'd like to do is define some function: def plone(x): return x+1 and then apply it elementwise to a 2-D numarray. I intend to treat the function as a variable, so ufuncs are probably not appropriate-- I
3
3384
by: PL | last post by:
I want to pass a 2D array from Python to C++, manipulate it in C++ (for example, add 1 to each element) and pass it back to Python. With these building blocks I will be able to figure out all the rest of what I need to do for my project. I am very familiar with Python, but less so with C++ and Boost or SWIG. Does anyone have an example with all steps that I can follow? More specifically I am looking for the C++ code, ".i" file for...
0
1237
by: andrewfelch | last post by:
Below is the code to/from Boolean arrays and Unsigned integers. On my Pentium 4, functions such as "bitwise_and" are 32 times faster when run on 32-bit integers instead of the entire-byte-consuming-Boolean. Good luck all:-) uint32Mask = numarray.array(, numarray.UInt32) uint32MaskInner = numarray.copy.deepcopy(uint32Mask) uint32MaskInner.shape =
0
7886
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8272
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8258
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5431
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3886
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3927
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2404
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1494
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1238
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.