Thanks for the example. I might stick to just not using the [][] so it would be less confusing to read how the class is constructed.
On Feb 12, 8:16 am, Ofer Koren <[email protected]> wrote: > you could do that if you create another object class with the getitem magic. > then return that object from your getitem method > > class SubItem: > > def __init__(self, parent, idx): > self.parent = parent > self.idx = idx > def __getitem__(self, subIdx): > return self.parent.data[self.idx * subIdx] > # or, for further sub-indexing: > return SubItem(self, self.idx * subIdx) > > class Foo: > def __init__(self, data): > ... > def __getitem__(self, idx): > return SubItem(self, idx) > > ...something along these lines... > Could get a bit messy though, you'd probably want SubItem to behave like a > number by itself, so you'd need to overload all of its numerical operators. > > Ofer > > > > On Thu, Feb 12, 2009 at 1:36 AM, ryant <[email protected]> wrote: > > > I guess this does an ok job, it doesnt give me the [][] overload > > though. > > > class flatMatrix(): > > > def __init__(self, data): > > self.data = data > > self.dim = 3 > > > def __getitem__(self, index): > > return self.data[index] > > > def __setitem__(self, key, item): > > self.data[key] = item > > > def __call__(self, indexA, indexB): > > index = (indexA * self.dim) + indexB > > return index > > > fm = flatMatrix( [1, 2, 3, > > 4, 5, 6, > > 7, 8, 9] ) > > print fm[fm (2,0)] > > > RyanT > > Technical Artist > > Naughty Dog Inc. > >www.rtrowbridge.com/blog > > > On Feb 12, 12:47 am, ryant <[email protected]> wrote: > > > I asked a question along these lines a few posts back, but I am > > > finding it difficult and possibly impossible to imitate one of the > > > features I found in this c++ class. So say I have a class: > > > > class foo(): > > > > def __init__(self, data): > > > self.data = data > > > > def __getitem__(self, index): > > > return self.data[index] > > > > def __setitem__(self, key, item): > > > self.data[key] = item > > > > This allows me to do this: > > > > obj = foo( [1, 2, 3, 4, 5, 6] ) > > > print obj[1] > > > > Now what I want to do, at least what this C++ program is doing is > > > this: > > > > print obj[1][1] > > > > Is there a way to overload the [ ] operators twice in a row like that? > > > Or do I have no choice but to create an array in an array if I want to > > > mimic the C++ program. I guess I could just use __call__ to return the > > > index needed to retrieve the correct index from the matrix and write > > > something like this: > > > > print obj[obj(1,1)] > > > > But that doesnt look as clear as [1][1] and I just want to know if its > > > possible. > > > > RyanT > > > Technical Artist > > > Naughty Dog Inc.www.rtrowbridge.com/blog > > -- > > - Oferwww.mrbroken.com --~--~---------~--~----~------------~-------~--~----~ Yours, Maya-Python Club Team. -~----------~----~----~----~------~----~------~--~---
