Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum two list in class
#3
Python is very flexible, so you can create your own types and operations.
Here a example with +, -, *, /, //, %, format()

The __r-Methods__ are used, if the left operand does not support the operation.
If you have on the left side a regular list and want to add it to MyList, the __radd__ method from MyList is used.
Same with other operations.

from operator import (
    add,
    sub,
    mul,
    truediv,
    floordiv,
    mod,
)
from numbers import Number
from itertools import tee


# inherit from list
class MyList(list):
    def __init__(self, iterable=None):
        if not iterable:
            iterable = []
        # tee creates by default from on iterator, two
        # independend iterators
        to_check, iterable = tee(iterable)
        # allows the use of generators,
        # but is not memory efficient
        for element in to_check:
            if not isinstance(element, Number):
                raise TypeError('Only Numbers are allowed')
        # init the list itself
        super().__init__(iterable)

    def _op(self, op, other):
        """
        Helper function to apply the operation on both lists.
        """
        if len(self) != len(other):
            raise TypeError('Lists have different sizes')
        return self.__class__(op(a, b) for a, b in zip(self, other))

    def __add__(self, other):
        return self._op(add, other)

    def __sub__(self, other):
        return self._op(sub, other)

    def __mul__(self, other):
        return self._op(mul, other)

    def __truediv__(self, other):
        return self._op(truediv, other)

    def __floordiv__(self, other):
        return self._op(floordiv, other)

    def __mod__(self, other):
        return self._op(mod, other)

    def __format__(self, fmt):
        """
        Controls the deleimiter used with format method or
        format string
        """
        return fmt.join(map(str, self))


    __radd__ = __add__
    __rsub__ = __sub__
    __rmul__ = __mul__
    __rfloordiv__ = __floordiv__
    __rtruediv__ = __truediv__
    __rmod__ = __mod__



my_list1 = MyList([10,20,30])
my_list2 = MyList([1,2,3])
regular_list1 = [10,20,30]
regular_list2 = [1,2,3]

# __add__, __sub__, ...
print(
    my_list1 + my_list2,
    my_list1 - my_list2,
    my_list1 * my_list2,
    my_list1 / my_list2,
    my_list1 // my_list2,
    my_list1 % my_list2,
)

# __add__, __sub__, ...
print(
    my_list1 + regular_list2,
    my_list1 - regular_list2,
    my_list1 * regular_list2,
    my_list1 / regular_list2,
    my_list1 // regular_list2,
    my_list1 % regular_list2,
)

# __radd__, __rsub__, ...
print(
    regular_list1 + my_list2,
    regular_list1 - my_list2,
    regular_list1 * my_list2,
    regular_list1 / my_list2,
    regular_list1 // my_list2,
    regular_list1 % my_list2,
)


some_result = regular_list1 + my_list2
my_delimiter = ' || '
print(f'{some_result:{my_delimiter}}')
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Sum two list in class - by no_named_nobody - Oct-17-2019, 06:00 PM
RE: Sum two list in class - by scidam - Oct-18-2019, 07:03 AM
RE: Sum two list in class - by DeaD_EyE - Oct-18-2019, 08:11 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Generating a list to feed into a class object zizi 0 2,382 Nov-02-2018, 01:50 PM
Last Post: zizi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020