[Numpy-discussion] subclassing ndaray
Stefan van der Walt
stefan at sun.ac.za
Fri Feb 24 11:16:03 CST 2006
I see the same strange result. Here is a minimal code example to
demonstrate:
import numpy as N
class Bar(N.ndarray):
v = 0.
def __new__(cls, *args, **kwargs):
print "running new"
return super(Bar, cls).__new__(cls, *args)
def __init__(self, *args, **kwargs):
print "running init"
self[:] = 0
self.v = 3
In [88]: b = Bar(3)
running new
running init
In [89]: b
Out[89]: Bar([0, 0, 0])
In [90]: b.v
Out[90]: 3
In [91]: c = b+1
In [92]: c.v
Out[92]: 0.0
However, if I do b[:] = 1, everything works fine.
Stéfan
On Fri, Feb 24, 2006 at 10:56:02AM -0500, Colin J. Williams wrote:
> I have a subclass Bar, a 1-dim array which has some methods and some
> attributes. One of the attributes is a view of the Bar to permit
> different shaping.
>
> Suppose that 'a' is an instance of 'Bar', which has a method 'show' and
> a view attribute 'v'.
>
> a ^ 15 returns a Bar instance, with its methods but without the attributes.
>
> I am attempt to change this, Bar has a method __xor__, see below:
>
> def __xor__(self, other):
> ''' Exclusive or: __xor__(x, y) => x ^ y . '''
> z=
> 1
> << this loops to the recursion limit
> result= ArrayType.__xor__(self, other)
> n= self.n
> result.n= n
> result.rowSize= self.rowSize
> result.show= self.show
> result.v= _n.reshape(result.view(), (n*n, n*n))
> return result
>
> Could anyone suggest a workaround please?
>
> Colin W.
More information about the Numpy-discussion
mailing list