Home > Enterprise >  How to sum and multiply two class instances
How to sum and multiply two class instances

Time:04-29

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

CodePudding user response:

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.

CodePudding user response:

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)
  • Related