0

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
Big Bean
  • 1
  • 1
  • 1
    What error? What's the expected result? (E.g., `MyList([1,2,3]) / 4 == MyList([1,2,3,4])`?) – chepner Jul 29 '21 at 16:10
  • TypeError: unsupported operand type(s) for /: 'list' and 'list' – Big Bean Jul 29 '21 at 16:12
  • TypeError: unsupported operand type(s) for /: 'list' and 'int' – Big Bean Jul 29 '21 at 16:12
  • show example which you run to get this error. Why do you use `__add__` inside `__div___`? It will need `for`-loop. – furas Jul 29 '21 at 21:47
  • Python 3.x uses `__truediv__` for `/` and `__floordiv__` for `//`. And `__div__` is 2.x-only. See link to [Python Class __div__ issue](https://stackoverflow.com/questions/21692065/python-class-div-issue). See also documentation for [operator](https://docs.python.org/3/library/operator.html). And `@` needs `__matmul__` – furas Jul 29 '21 at 22:37

0 Answers0