As i said in topic i need to create class that can be sum by other class and also multiply. Below present expected result and code behaviour.
v1 = Vector([1, 2, 1, 5]) - class 1 called Vector v2 = Vector([2, 3, 1, 4]) - class 2 called Vector # [1+2, 2+3, 1+1, 5+4] - expected sums v3 = v1 + v2 v3.get_vals() [3, 5, 2, 9] - expected result # 1*2 + 2*3 + 1*1 + 5*4 - multiplication v1 * v2 29
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can define __add__, __mul__ and other dunder methods.
For example:
class Vector:
def __init__(self, arr):
self.arr = list(arr)
def __add__(self, other):
return Vector(a + b for a, b in zip(self.arr, other.arr))
def __mul__(self, other):
return sum(a * b for a, b in zip(self.arr, other.arr))
def get_vals(self):
return self.arr
v1 = Vector([1, 2, 1, 5])
v2 = Vector([2, 3, 1, 4])
v3 = v1 + v2
assert [3, 5, 2, 9] == v3.get_vals()
assert v1 * v2 == 29
I do suggest using packages such as numpy for that instead of reinventing the wheel.
Method 2
I’m going to break this down a little bit.
First you have Python’s magic methods which allow any class to utilize operators like + or *.
Second you have zip which will allow you to map elements from two (or more) iterables to each other.
Third list comprehension will allow a new list to be constructed in place with a forloop.
class Vector:
def __add__(self, other):
return self.__class__([x + y for x, y in zip(self.values, other.values)])
def __mul__(self, other):
return self.__class__([x * y for x, y in zip(self.values, other.values)])
I would recommend using a helper method and the operator library to avoid duplicating bits of your code.
class Vector:
def new(self, other, operator_):
return self.__class__([operator_(*x) for x in zip(self.values, other.values)])
def __add__(self, other):
return self.new(other, operator.add)
def __mul__(self, other):
return self.new(other, operator.mul)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0