From bb5810c2b49eb2c6e05813843909bfae35805674 Mon Sep 17 00:00:00 2001 From: Nikolay <58514394+nocarend@users.noreply.github.com> Date: Mon, 1 Apr 2024 12:17:50 +0700 Subject: [PATCH] add self with casting --- problems-3/n-valikov/problem3.py | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/problems-3/n-valikov/problem3.py b/problems-3/n-valikov/problem3.py index c11a5244..d20000ef 100644 --- a/problems-3/n-valikov/problem3.py +++ b/problems-3/n-valikov/problem3.py @@ -1,11 +1,9 @@ import unittest from numbers import Number -from typing import Tuple, Any, TypeAlias +from typing import Tuple, Any, Self class Vector: - Vector: TypeAlias = Vector - _content: Tuple _iter_counter: int @@ -16,20 +14,20 @@ def __init__(self, content: Tuple): self._content = content self._iter_counter = 0 - def __add__(self, other: Vector) -> Vector: + def __add__(self, other: Self) -> Self: if len(self) != len(other): raise ValueError('Vectors dimensions must be equal') - return Vector(tuple(first + second for first, second in zip(self._content, other._content))) + return type(self)(tuple(first + second for first, second in zip(self._content, other._content))) - def __sub__(self, other: Vector) -> Vector: + def __sub__(self, other: Self) -> Self: return self + (-other) - def __neg__(self) -> Vector: - return Vector(tuple(-value for value in self._content)) + def __neg__(self) -> Self: + return type(self)(tuple(-value for value in self._content)) - def __mul__(self, constant: int) -> Vector: - return Vector(tuple(content * constant for content in self._content)) + def __mul__(self, constant: int) -> Self: + return type(self)(tuple(content * constant for content in self._content)) def __next__(self): length = len(self) @@ -57,11 +55,11 @@ def __str__(self): return (f"Number of dimensions: {len(self._content)}\n" f"{'\n'.join(map(lambda value: str(value), self._content))}\n") - def scalar_product(self, other: Vector) -> Vector: + def scalar_product(self, other: Self) -> Self: if len(self) != len(other): raise ValueError('Vectors dimensions must be equal') - return Vector( + return type(self)( tuple(this_content * other_content for this_content, other_content in zip(self._content, other._content)))