Commit 37505baf by Patryk Czarnik

magiczne metody

parent 0cf59f3d
class Liczba:
def __init__(self, x=0):
self.x = x
# repr ma zwrócić tekstową postać obiektu, ale zapisaną "technicznie"
# tak, aby dało się to wkleić do kodu Pythona
def __repr__(self):
return f'Liczba({self.x})'
# str ma zwrócić tekstową postać obiektu, ale przeznaczoną dla człowieka
def __str__(self):
return f'[{self.x}]'
# Aby określić, jak ma działać dodawanie (operator +) dla obiektów naszej klasy,
# definiujemy metodę __add__, gdzie lewy i prawy argument są przekazywane
# jako self i other
def __add__(self, other):
return Liczba(self.x + other.x)
# sub, mul, truediv, floordiv, mod
# wersje z literą 'r' na początku - odwrócona kolejność argumentów
# wersja z 'i' na początku - zmiana wartości "w miejscu", czyli + , *= itp.
def __eq__(self, other):
return self.x == other.x
# lt, le, gt, ge, ne do pozostałych porównań
# ne nie trzeba implementować, bo jest negacją eq
liczba1 = Liczba(3)
liczba2 = Liczba(5)
print('str:', str(liczba1))
print('repr:', repr(liczba1))
print()
print(liczba1, liczba2)
suma = liczba1 + liczba2
print('suma:', suma, 'typu', type(suma))
print(suma == Liczba(8))
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