Back to Freecodecamp

Step 51

curriculum/challenges/english/blocks/learn-special-methods-by-building-a-vector-space/65fa9e1b6c6db919385359ec.md

latest1.9 KB
Original Source

--description--

The special method __mul__ can be implemented to specify what should happen when the current instance is multiplied by another object.

Create an empty __mul__ method within the R2Vector class and give it two parameters: self, and other.

--hints--

You should define a __mul__ method within the R2Vector class.

js
({
    test: () => assert(runPython(`
      _Node(_code).find_class("R2Vector").has_function("__mul__")
    `))
})

Your __mul__ method should have two parameters, self and other.

js
({
    test: () => assert(runPython(`
      _Node(_code).find_class("R2Vector").find_function("__mul__").has_args("self, other")
    `))
})

--seed--

--seed-contents--

py
class R2Vector:
    def __init__(self, *, x, y):
        self.x = x
        self.y = y

    def norm(self):
        return sum(val**2 for val in vars(self).values())**0.5

    def __str__(self):
        return str(tuple(getattr(self, i) for i in vars(self)))

    def __repr__(self):
        arg_list = [f'{key}={val}' for key, val in vars(self).items()]
        args = ', '.join(arg_list)
        return f'{self.__class__.__name__}({args})'

    def __add__(self, other):
        if type(self) != type(other):
            return NotImplemented
        kwargs = {i: getattr(self, i) + getattr(other, i) for i in vars(self)}
        return self.__class__(**kwargs)

    def __sub__(self, other):
        if type(self) != type(other):
            return NotImplemented
        kwargs = {i: getattr(self, i) - getattr(other, i) for i in vars(self)}
        return self.__class__(**kwargs)
--fcc-editable-region--
    
--fcc-editable-region--
class R3Vector(R2Vector):
    def __init__(self, *, x, y, z):
        super().__init__(x=x, y=y)
        self.z = z

v1 = R2Vector(x=2, y=3)
v2 = R2Vector(x=0.5, y=1.25)
print(f'v1 = {v1}')
print(f'v2 = {v2}')
v3 = v1 + v2
print(f'v1 + v2 = {v3}')
v4 = v1 - v2
print(f'v1 - v2 = {v4}')