I'd like to define a custom operation between a list and an integer for entry-wise product and entry-wise addition, and if possible using a symbol like / or @.
I tried setting up a __div__
method like:
def __div__(self, rhs):
return MyList(list.__add__(self, rhs))
def __div__(self, rhs):
return MyList(int.__add__(self, rhs))
but an error message popped up.
(Edit: the error messages are:
TypeError: unsupported operand type(s) for /: 'list' and 'list'
TypeError: unsupported operand type(s) for /: 'list' and 'int'
)
How can I do that?
Here is my custom class:
from collections.abc import MutableSequence
class MyList(MutableSequence):
"""A container for manipulating lists of hosts"""
def __init__(self, data=None):
"""Initialize the class"""
super(MyList, self).__init__()
if (data is not None):
self._list = list(data)
else:
self._list = list()
self.Color = 'k'
def __repr__(self):
return "<{0} {1}>".format(self.__class__.__name__, self._list)
def __len__(self):
"""List length"""
return len(self._list)
def __getitem__(self, ii):
"""Get a list item"""
return self._list[ii]
def __delitem__(self, ii):
"""Delete an item"""
del self._list[ii]
def __setitem__(self, ii, val):
# optional: self._acl_check(val)
self._list[ii] = val
def __str__(self):
return str(self._list)
def insert(self, ii, val):
# optional: self._acl_check(val)
self._list.insert(ii, val)
def append(self, val):
self.insert(len(self._list), val)
def __getslice__(self,i,j):
return MyList(list.__getslice__(self, i, j))
def __mul__(self,other):
return MyList(list.__mul__(self,other))
def __add__(self, rhs):
return MyList(list.__add__(self, rhs))
def color(self, *args):
"Color of strand."
if args != ():
self.Color = args[0]
else:
return self.Color