Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload [] python operator and chaining methods using a memory reference

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

Imagine I have a class Math that accepts a list of integer numbers, like this:

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 could do something like add_one(2,4), but this is not the style of API I would like to have if possible.

Thanks

like image 724
maraujop Avatar asked Jun 09 '12 16:06

maraujop


1 Answers

As Winston mentions, you need to implement an auxiliary 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 the math object with the MathSlice object depends on what you want the semantics to be if the math object changes.

like image 159
Ned Batchelder Avatar answered Nov 11 '22 07:11

Ned Batchelder