Overloading [] The python operator and chaining methods using memory references

Is it possible to overload the [] (__getitem__) operator methods and Python chains using the original memory reference.

Suppose I have a Math class that accepts a list of integers, for example:

 class Math(object): def __init__(self, *args, **kwargs): assert(all([isinstance(item, int) for item in list(args)])) self.list = list(args) def add_one(self): for index in range(len(self.list)): self.list[index] += 1 

And I want to do something like this:

 instance = Math(1,2,3,4,5) instance[2:4].add_one() 

After executing this code, instance.list should be [1,2,4,5,5] , is this possible?

I know I can do something like add_one(2,4) , but that is not the style of the API that I would like to have, if possible.

thanks

+7
source share
2 answers

As Winston mentions, you need to implement a helper object:

 class Math(object): def __init__(self, *args, **kwargs): self.list = list(args) def __getitem__(self, i): return MathSlice(self, i) class MathSlice(object): def __init__(self, math, slice): self.math = math self.slice = slice def add_one(self): for i in xrange(*self.slice.indices(len(self.math.list))): self.math.list[i] += 1 instance = Math(1,2,3,4,5) instance[2:4].add_one() print instance.list 

How you share a math object with a MathSlice object depends on what you want the semantics to be if the math object changes.

+9
source

Numpy is doing something like this.

The __getitem__ method will get a slice object. See http://docs.python.org/reference/datamodel.html for more details. You will need to return a new object, but implement this object in such a way that it modifies the original list.

+5
source

All Articles