Zanurkuj w Pythonie/Metody specjalne: Różnice pomiędzy wersjami
Usunięta treść Dodana treść
tłumaczenie |
drobne poprawki formatowania |
||
Linia 5:
Jak zauważyłeś w poprzednim rozdziale, użycie normalnych metod pozwalają zrobić duży krok w stronę obudowania słownika klasą. Ale ponieważ możesz zrobić ze słownikiem dużo więcej, niż wywołać jego metody, normalne metody nie wystarcza. Możesz na przykład pobierać i dodawać elementy, używając składni nie wywołując metod jawnie. W tym przypadku przydadzą się klasy specjale, które pozwalają zmapować elementy składni na wywołania metod.
'''Przykład 5.12 Metoda <tt>__getitem__</tt>'''
def __getitem__(self, key): return self.data[key]
Linia 22:
Of course, Python has a __setitem__ special method to go along with __getitem__, as shown in the next example.
'''Example 5.13. The __setitem__ Special Method'''
def __setitem__(self, key, item): self.data[key] = item
Linia 43:
For example, MP3FileInfo is a descendant of FileInfo. When an MP3FileInfo's name is set, it doesn't just set the name key (like the ancestor FileInfo does); it also looks in the file itself for MP3 tags and populates a whole set of keys. The next example shows how this works.
Example 5.14. Overriding __setitem__ in MP3FileInfo▼
▲'''Example 5.14. Overriding __setitem__ in MP3FileInfo'''
def __setitem__(self, key, item): #(1)
if key == "name" and item: #(2)
Linia 57:
When accessing data attributes within a class, you need to qualify the attribute name: self.attribute. When calling other methods within a class, you need to qualify the method name: self.method.
'''Example 5.15. Setting an MP3FileInfo's name'''
>>> import fileinfo
|