__getslice__
Stuart Reynolds
S.I.Reynolds at cs.bham.ac.uk
Mon Nov 29 13:07:39 EST 1999
Hmm. Ok. How do slices work then?
I've written a class to do some simple structuring of data so that its
easy to plot (with, say, Gnuplot.py). The class c'tor takes:
- a sequence of input values [i1, i2, ... , in]
- a function, f(i) --> outputi
and the objects represent the sequence:
- ( (i1, f(i1)),
(i2, f(i2)),
...
(in, f(in)), )
Things like __repr__, __len__, __getitem__ all work as expected, but
__getslice__ behaves very oddly - which is strange since it all seems
fairly straightforward.
Any help muchly appreciated,
Stu
----------------
>>> def square(x):
return x*x
>>> xvals = [0,1,2,3,4,5,6,7]
>>> a = UnaryFnSequence(square, xvals)
>>> xvals[1:]
[1, 2, 3, 4, 5, 6, 7]
>>> a
( (0,0), (1,1), (2,4), (3,9), (4,16), (5,25), (6,36), (7,49) )
>>> a[1:]
( (0,0), (1,1), (2,4), (3,9), (4,16), (5,25), (6,36) )
Note that the first item is still there. The last one's gone instead.
The class:
class UnaryFnSequence:
"""
The constructor takes two arguments:
fn -- A unary function
inputs -- An ordered sequence of inputs to the sequences,
(i1, i2, ..., in)
The class represents the following immutable sequence:
( (i1, fn(i1)),
(i2, fn(i2)),
...
(in, fn(in)),
)
Slices aren't supported yet.
"""
def __init__(self, fn, inputs):
self._inputs = inputs
self._fn = fn
def __len__(self):
return len(self._inputs)
def __getitem__(self, index):
x = self._inputs[index]
return x, self._fn( x )
def __repr__(self):
s='( '
for x in range( len(self) ):
s = s+'('+`x`+','+`self._fn(x)`+'), '
return s[:-2] + ' )'
def __getslice__(self, low, high):
return UnaryFnSequence(self._fn, self._inputs[low:high] )
More information about the Python-list
mailing list