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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With