Commit 2d0b7e2c by Patryk Czarnik

klasa Vector

parent f30c91ba
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Vector({self.x},{self.y})'
def __str__(self):
return f'<{self.x},{self.y}>'
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, liczba):
return Vector(self.x * liczba, self.y * liczba)
def __rmul__(self, liczba):
return self.__mul__(liczba)
# dekorator @property powoduje, że aby odczytać wynik tej metody, nie używa się już wywołania
# v.dlugosc()
# tylko stosuje się zapis taki jak przy odczycie atrybutu (zmiennej)
# v.dlugosc
@property
def dlugosc(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
def __eq__(self, other):
return self.dlugosc == other.dlugosc
def __lt__(self, other):
return self.dlugosc < other.dlugosc
def __le__(self, other):
return self.dlugosc <= other.dlugosc
def __gt__(self, other):
return self.dlugosc > other.dlugosc
def __ge__(self, other):
return self.dlugosc >= other.dlugosc
def __bool__(self):
return self.dlugosc != 0.0
def proste_testy():
a = Vector(3, 4)
b = Vector(5, 11)
print('a:', a)
print('b:', b)
print('repr a:', repr(a))
print('repr b:', repr(b))
print()
wynik = a + b
print(wynik)
wynik = a - b
print(wynik)
wynik = a * 5
print(wynik)
wynik = 4 * b
print(wynik)
print(a.dlugosc)
print(b.dlugosc)
if a:
print('Wektor nie jest zerowy')
# Ten warunek jest prawdziwy, gdy plik jest uruchamiany bezpośrednio jako program.
# A nie jest prawdziwy, gdy ten plik jest importowany z innego.
# Taki charakterystyczny if zapobiega wykonaniu instrukcji, gdy plik źródłowy jest importowany.
if __name__ == '__main__':
proste_testy()
from vector import Vector
def test_str():
v = Vector(5, 12)
s = str(v)
assert s == '<5,12>'
def test_repr():
v = Vector(5, 12)
r = repr(v)
assert r == 'Vector(5,12)'
new_vector = eval(r)
assert isinstance(new_vector, Vector)
assert new_vector.x == 5
assert new_vector.y == 12
def test_add():
a = Vector(3, 4)
b = Vector(5, 12)
suma = a + b
assert isinstance(suma, Vector)
assert suma.x == 8
assert suma.y == 16
def test_sub():
a = Vector(3, 4)
b = Vector(5, 12)
wynik = b - a
assert isinstance(wynik, Vector)
assert wynik.x == 2
assert wynik.y == 8
def test_mul():
a = Vector(3, 4)
wynik = a * 3
assert isinstance(wynik, Vector)
assert wynik.x == 9
assert wynik.y == 12
def test_rmul():
a = Vector(3, 4)
wynik = 2 * a
assert isinstance(wynik, Vector)
assert wynik.x == 6
assert wynik.y == 8
def test_eq():
a = Vector(3, 4)
b = Vector(4, 3)
c = Vector(5, 0)
d = Vector(3, 3)
assert a == a
assert a == b
assert a == c
assert a != d
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment