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}}')