Metody magiczne w Pythonie
Ten artykuł wyjaśnia metody magiczne w Pythonie.
YouTube Video
Metody magiczne w Pythonie
Metody magiczne (specjalne) w Pythonie to specjalnie nazwane metody, które nadają klasom unikalne zachowania. Charakteryzują się tym, że są otoczone podwójnymi podkreśleniami (dunders), na przykład __init__ i __str__. Dlatego nazywane są również metodami dunder.
Definiując metody magiczne, możesz dostosować standardowe zachowanie klas. Na przykład zdefiniowanie __add__ pozwala zmienić działanie operatora +.
Metody magiczne do inicjalizacji i reprezentacji tekstowej
__init__: Metoda inicjalizacyjna
Metoda __init__ to konstruktor wywoływany automatycznie podczas tworzenia instancji.
1class Person:
2 def __init__(self, name, age):
3 self.name = name
4 self.age = age
5
6person = Person("Alice", 30)
7print(person.name) # Alice__str__: Reprezentacja tekstowa czytelna dla człowieka
Metoda __str__ zwraca czytelną dla człowieka reprezentację tekstową. Jest wywoływana przez print() oraz str().
1class Person:
2 def __init__(self, name):
3 self.name = name
4
5 def __str__(self):
6 return f"Person: {self.name}"
7
8person = Person("Bob")
9print(person) # Person: Bob__repr__: Tekstowa reprezentacja do celów debugowania
Metoda __repr__ zwraca tekstową reprezentację do celów debugowania. Jest używana przez repr() oraz podczas wyświetlania w interpreterze.
1class Person:
2 def __init__(self, name):
3 self.name = name
4
5 def __repr__(self):
6 return f"Person(name={self.name!r})"
7
8person = Person("Eve")
9print(repr(person)) # Person(name='Eve')Przeciążanie operatorów arytmetycznych
__add__: Operator +
Za pomocą metod magicznych można przeciążać operatory arytmetyczne. Na przykład metoda __add__ umożliwia przeciążenie operatora +.
1class Vector:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5
6 def __add__(self, other):
7 return Vector(self.x + other.x, self.y + other.y)
8
9 def __repr__(self):
10 return f"Vector({self.x}, {self.y})"
11
12 # Other arithmetic magic methods:
13 # def __sub__(self, other): # Subtraction (-)
14 # def __mul__(self, other): # Multiplication (*)
15 # def __truediv__(self, other): # True division (/)
16 # def __floordiv__(self, other): # Floor division (//)
17 # def __mod__(self, other): # Modulo (%)
18 # def __pow__(self, other): # Exponentiation (**)
19
20v1 = Vector(1, 2)
21v2 = Vector(3, 4)
22print(v1 + v2) # Vector(4, 6)Do innych arytmetycznych metod magicznych należą:.
| Metoda | Operator |
|---|---|
__add__ |
+ |
__sub__ |
- |
__mul__ |
* |
__truediv__ |
/ |
__floordiv__ |
// |
__mod__ |
% |
__pow__ |
** |
Dostosowywanie operatorów porównania
Możesz również przeciążać operatory porównania. Na przykład metoda __eq__ przeciąża operator równości.
1class Box:
2 def __init__(self, volume):
3 self.volume = volume
4
5 def __eq__(self, other):
6 return self.volume == other.volume
7
8 def __lt__(self, other):
9 return self.volume < other.volume
10
11 # Comparison magic methods:
12 # def __eq__(self, other): # Equal to (==)
13 # def __ne__(self, other): # Not equal to (!=)
14 # def __lt__(self, other): # Less than (<)
15 # def __le__(self, other): # Less than or equal to (<=)
16 # def __gt__(self, other): # Greater than (>)
17 # def __ge__(self, other): # Greater than or equal to (>=)
18
19b1 = Box(100)
20b2 = Box(200)
21
22print(b1 == b2) # False
23print(b1 < b2) # TrueWystępują także następujące metody magiczne:. Te metody magiczne definiują porównania takie jak równość i porządkowanie pomiędzy obiektami.
| Operator | Metoda magiczna |
|---|---|
== |
__eq__ |
!= |
__ne__ |
< |
__lt__ |
<= |
__le__ |
> |
__gt__ |
>= |
__ge__ |
Metody magiczne dla typów kontenerowych
Możesz tworzyć klasy zachowujące się jak listy lub słowniki.
__len__: Pobieranie liczby elementów
Metoda __len__ to metoda magiczna, która zwraca liczbę elementów.
1class Basket:
2 def __init__(self, items):
3 self.items = items
4
5 def __len__(self):
6 return len(self.items)
7
8basket = Basket(["apple", "banana"])
9print(len(basket)) # 2__getitem__: Dostęp przez indeks
Metoda __getitem__ jest wywoływana podczas korzystania z dostępu przez indeks.
1class Basket:
2 def __init__(self, items):
3 self.items = items
4
5 def __getitem__(self, index):
6 return self.items[index]
7
8basket = Basket(["apple", "banana"])
9print(basket[1]) # banana__setitem__ i __delitem__: Zapisywanie i usuwanie
Metody __setitem__ i __delitem__ są wywoływane podczas zapisywania lub usuwania elementów.
1class Basket:
2 def __init__(self, items):
3 self.items = items
4
5 def __setitem__(self, index, value):
6 self.items[index] = value
7
8 def __delitem__(self, index):
9 del self.items[index]
10
11basket = Basket(["apple", "banana"])
12basket[1] = "grape"
13del basket[0]
14print(basket.items) # ['grape']Metody magiczne do iteracji
Aby obiekt był iterowalny w pętli for, zaimplementuj następujące metody:.
__iter__ i __next__
1class Counter:
2 def __init__(self, limit):
3 self.limit = limit
4 self.current = 0
5
6 def __iter__(self):
7 return self
8
9 def __next__(self):
10 if self.current >= self.limit:
11 raise StopIteration
12 self.current += 1
13 return self.current
14
15for num in Counter(3):
16 print(num)
17# Output:
18# 1
19# 2
20# 3Menadżer kontekstu (with)
Definiując metody __enter__ i __exit__, możesz zaimplementować działania przed i po użyciu instrukcji with.
1class FileOpener:
2 def __init__(self, filename):
3 self.filename = filename
4
5 def __enter__(self):
6 self.file = open(self.filename, 'r')
7 return self.file
8
9 def __exit__(self, exc_type, exc_val, exc_tb):
10 self.file.close()
11
12with FileOpener("example.txt") as f:
13 content = f.read()
14 print(content)Obiekty wywoływalne: __call__
Definiując metodę __call__, możesz sprawić, że instancja będzie wywoływalna jak funkcja.
1class Greeter:
2 def __init__(self, greeting):
3 self.greeting = greeting
4
5 def __call__(self, name):
6 return f"{self.greeting}, {name}!"
7
8hello = Greeter("Hello")
9print(hello("Alice")) # Hello, Alice!Podsumowanie
Metody magiczne w Pythonie są potężnym sposobem na dodanie naturalnego i intuicyjnego zachowania klasom. Każda z tych metod ma jasno określony cel, a ich odpowiednie zaimplementowanie pozwala pisać bardziej elastyczny i pythoniczny kod.
Metody magiczne stanowią 'niewidzialny interfejs', który wspiera sposób, w jaki obiekty Pythona współdziałają i zachowują się w tle.
Możesz śledzić ten artykuł, korzystając z Visual Studio Code na naszym kanale YouTube. Proszę również sprawdzić nasz kanał YouTube.