Несколько выходит за рамки вашего фактического вопроса, но вы можете использовать некоторые функции magi c, чтобы абстрагироваться от деталей:
class MyCoolList(list):
def __sub__(self, other):
return [item - other for item in self]
def __add__(self, other):
return [item + other for item in self]
def __mul__(self, other):
return [item * other for item in self]
Теперь мы можем сделать:
cls = MyCoolList([9, 3, 5, 2])
print(cls - 1)
print(cls + 1)
print(cls * 2)
Что дает
[8, 2, 4, 1]
[10, 4, 6, 3]
[18, 6, 10, 4]
Чтобы не повторяться (DRY
), вы вполне можете использовать модуль operator
:
import operator as op
class MyCoolList(list):
def calc(self, what, other):
return [what(item, other) for item in self]
def __sub__(self, other):
return self.calc(op.sub, other)
def __add__(self, other):
return self.calc(op.add, other)
def __mul__(self, other):
return self.calc(op.mul, other)
В конце , вы можете вообще использовать декоратор:
import operator as op
def calc(operator_function):
def real_decorator(function):
def wrapper(*args, **kwargs):
lst, other = args
return [operator_function(item, other) for item in lst]
return wrapper
return real_decorator
class MyCoolList(list):
@calc(op.sub)
def __sub__(self, other):
pass
@calc(op.add)
def __add__(self, other):
pass
@calc(op.mul)
def __mul__(self, other):
pass
cls = MyCoolList([9, 3, 5, 2])
print(cls - 1)
print(cls + 1)